<!DOCTYPE html>
<html>
<head>
    <title>实时聊天管理</title>
    {% include 'system/common/header.html' %}
    <style>
        @keyframes pulse {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.2); opacity: 0.7; }
            100% { transform: scale(1); opacity: 1; }
        }
        
        /* 管理员工具栏样式 */
        .admin-toolbar-btn {
            background: none;
            border: 1px solid #e0e0e0;
            padding: 6px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.2s;
            color: #666;
            min-width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .admin-toolbar-btn:hover {
            background: #f0f0f0;
            border-color: #1E9FFF;
            transform: translateY(-1px);
        }
        
        .admin-toolbar-btn:active {
            transform: translateY(0);
        }
        
        /* 表情项样式 */
        .admin-emoji-item {
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border-radius: 4px;
            font-size: 16px;
            transition: all 0.2s;
            user-select: none;
            border: 1px solid transparent;
        }
        
        .admin-emoji-item:hover {
            background: #f0f0f0;
            border-color: #1E9FFF;
            transform: scale(1.1);
        }
        
        /* 桌面共享弹窗样式 */
        #desktopSharePopup {
            transition: all 0.3s ease;
        }
        
        #desktopSharePopup.maximized {
            width: 95% !important;
            height: 95% !important;
            max-width: none !important;
            max-height: none !important;
            top: 2.5% !important;
            left: 2.5% !important;
            transform: none !important;
        }
        
        #desktopSharePopup.minimized {
            width: 300px !important;
            height: 200px !important;
            top: auto !important;
            left: 20px !important;
            bottom: 20px !important;
            transform: none !important;
        }
        
        #desktopSharePopup.fullscreen {
            width: 100vw !important;
            height: 100vh !important;
            top: 0 !important;
            left: 0 !important;
            transform: none !important;
            border-radius: 0 !important;
            z-index: 10001 !important;
        }
        
        #desktopSharePopup.fullscreen .desktop-share-header {
            border-radius: 0 !important;
        }
        
        #desktopSharePopup.fullscreen .desktop-share-video-container {
            border-radius: 0 !important;
        }
        
        .desktop-share-controls {
            display: flex;
            gap: 8px;
        }
        
        .desktop-share-control-btn {
            background: none;
            border: none;
            color: white;
            font-size: 16px;
            cursor: pointer;
            padding: 4px 8px;
            border-radius: 4px;
            transition: background 0.3s;
        }
        
        .desktop-share-control-btn:hover {
            background: rgba(255,255,255,0.2);
        }
        
        /* 桌面共享视频点击样式 */
        #adminDesktopShareRemoteVideo {
            transition: opacity 0.3s ease;
        }
        
        #adminDesktopShareRemoteVideo:hover {
            opacity: 0.9;
        }
        
        /* 暂停状态下的视觉提示 */
        #adminDesktopShareRemoteVideo.paused {
            opacity: 0.8;
        }
        
        /* 播放状态下的视觉提示 */
        #adminDesktopShareRemoteVideo.playing {
            opacity: 1;
        }
    </style>
</head>
<body class="ppress-container">
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <!-- 左侧会话列表 -->
        <div class="layui-col-md4">
            <div class="layui-card">
                <div class="layui-card-header" style="background: #f8f8f8; display: flex; align-items: center; justify-content: space-between;">
                    <div style="display: flex; align-items: center;">
                        <i class="layui-icon layui-icon-group"></i> 活跃会话列表
                        <span id="activeSessionCount" class="layui-badge layui-bg-blue" style="margin-left: 10px;">0</span>
                    </div>
                    <button id="refreshBtn" class="layui-btn layui-btn-xs layui-btn-normal">
                        <i class="layui-icon layui-icon-refresh-3"></i> 刷新
                    </button>
                </div>
                <div class="layui-card-body" style="padding: 0;">
                    <div id="sessionList" style="max-height: 600px; overflow-y: auto;">
                        <div id="noSessions" style="text-align: center; padding: 40px; color: #999;">
                            <i class="layui-icon layui-icon-face-cry" style="font-size: 48px; color: #ddd;"></i>
                            <div style="margin-top: 10px;">暂无活跃会话</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 右侧聊天详情 -->
        <div class="layui-col-md8">
            <div class="layui-card">
                <div class="layui-card-header" style="background: #f8f8f8; display: flex; align-items: center; justify-content: space-between;">
                    <span id="chatTitle">
                        <i class="layui-icon layui-icon-chat"></i> 选择一个会话开始聊天
                    </span>
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <!-- 连接状态 -->
                        <span id="connectionStatus" style="
                            display: inline-flex;
                            align-items: center;
                            padding: 6px 12px;
                            border-radius: 4px;
                            font-size: 12px;
                            color: white;
                            background: #ff5722;
                            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                            height: 26px;
                            line-height: 1;
                            box-sizing: border-box;
                        ">
                            <i class="layui-icon layui-icon-connection"></i> 连接状态: 断开
                        </span>
                        
                        <!-- 语音通话按钮 -->
                        <button id="adminVoiceCallBtn" onclick="handleAdminVoiceCall()" style="
                            display: none;
                            background: #1e88e5;
                            border: none;
                            color: white;
                            padding: 6px 12px;
                            border-radius: 4px;
                            cursor: pointer;
                            font-size: 12px;
                            height: 26px;
                            line-height: 1;
                            box-sizing: border-box;
                            margin-right: 8px;
                        ">
                            <i class="layui-icon layui-icon-voice"></i> <span id="adminCallBtnText">接听通话</span>
                        </button>
                        
                        <!-- 视频通话按钮 -->
                        <button id="adminVideoCallBtn" onclick="handleAdminVideoCall()" style="
                            display: none;
                            background: #9c27b0;
                            border: none;
                            color: white;
                            padding: 6px 12px;
                            border-radius: 4px;
                            cursor: pointer;
                            font-size: 12px;
                            height: 26px;
                            line-height: 1;
                            box-sizing: border-box;
                            margin-right: 8px;
                        ">
                            <i class="layui-icon layui-icon-video"></i> <span id="adminVideoCallBtnText">接听视频</span>
                        </button>
                        
                        <!-- 桌面共享按钮 -->
                        <button id="adminDesktopShareBtn" onclick="handleAdminDesktopShare()" style="
                            display: none;
                            background: #4caf50;
                            border: none;
                            color: white;
                            padding: 6px 12px;
                            border-radius: 4px;
                            cursor: pointer;
                            font-size: 12px;
                            height: 26px;
                            line-height: 1;
                            box-sizing: border-box;
                            margin-right: 8px;
                        ">
                            <i class="layui-icon layui-icon-screen"></i> <span id="adminDesktopShareBtnText">接听桌面共享</span>
                        </button>
                        
                        <!-- 拒绝通话按钮 -->
                        <button id="adminRejectCallBtn" onclick="rejectCall()" style="
                            display: none;
                            background: #f44336;
                            border: none;
                            color: white;
                            padding: 6px 12px;
                            border-radius: 4px;
                            cursor: pointer;
                            font-size: 12px;
                            height: 26px;
                            line-height: 1;
                            box-sizing: border-box;
                        ">
                            <i class="layui-icon layui-icon-close"></i> 拒绝
                        </button>
                        
                        <button id="closeSessionBtn" class="layui-btn layui-btn-sm layui-btn-danger" style="display: none; height: 26px; line-height: 1; box-sizing: border-box;">
                            <i class="layui-icon layui-icon-close"></i> 关闭会话
                        </button>
                    </div>
                </div>
                <div class="layui-card-body">
                    <!-- 聊天消息区域 -->
                    <div id="chatMessages" style="
                        height: 400px; 
                        overflow-y: auto; 
                        border: 1px solid #e6e6e6; 
                        padding: 15px; 
                        background: #fafafa;
                        border-radius: 4px;
                        margin-bottom: 15px;
                        box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
                    ">
                        <div style="text-align: center; color: #999; padding: 40px;">
                            <i class="layui-icon layui-icon-chat" style="font-size: 48px; color: #ddd;"></i>
                            <div style="margin-top: 10px;">请选择左侧会话开始聊天</div>
                        </div>
                    </div>
                    
                    <!-- 输入区域 -->
                    <div id="chatInputArea" style="display: none;">
                        <!-- 工具栏 -->
                        <div style="
                            border: 1px solid #e0e0e0; 
                            border-bottom: none; 
                            padding: 8px 12px; 
                            background: #fafafa; 
                            border-radius: 4px 4px 0 0;
                            display: flex;
                            align-items: center;
                            gap: 8px;
                            position: relative;
                        ">
                            <!-- 表情按钮 -->
                            <button onclick="toggleAdminEmoji()" class="admin-toolbar-btn" title="表情">
                                😊
                            </button>
                            
                            <!-- 表情面板 -->
                            <div id="adminEmojiPanel" style="
                                position: absolute;
                                bottom: 100%;
                                left: 0;
                                width: 300px;
                                background: white;
                                border: 1px solid #e0e0e0;
                                border-radius: 8px;
                                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                                display: none;
                                z-index: 1000;
                                margin-bottom: 8px;
                                overflow: hidden;
                            ">
                                <div style="padding: 12px; border-bottom: 1px solid #f0f0f0; font-weight: bold; color: #666; font-size: 14px;">
                                    选择表情
                                </div>
                                <div style="padding: 12px; max-height: 200px; overflow-y: auto;">
                                    <div style="margin-bottom: 10px;">
                                        <div style="font-size: 12px; color: #999; margin-bottom: 8px;">常用表情</div>
                                        <div style="display: grid; grid-template-columns: repeat(8, 1fr); gap: 8px;">
                                            <div onclick="insertAdminEmoji('😀')" class="admin-emoji-item">😀</div>
                                            <div onclick="insertAdminEmoji('😃')" class="admin-emoji-item">😃</div>
                                            <div onclick="insertAdminEmoji('😄')" class="admin-emoji-item">😄</div>
                                            <div onclick="insertAdminEmoji('😊')" class="admin-emoji-item">😊</div>
                                            <div onclick="insertAdminEmoji('😍')" class="admin-emoji-item">😍</div>
                                            <div onclick="insertAdminEmoji('🥰')" class="admin-emoji-item">🥰</div>
                                            <div onclick="insertAdminEmoji('😘')" class="admin-emoji-item">😘</div>
                                            <div onclick="insertAdminEmoji('🤗')" class="admin-emoji-item">🤗</div>
                                            <div onclick="insertAdminEmoji('🤔')" class="admin-emoji-item">🤔</div>
                                            <div onclick="insertAdminEmoji('😐')" class="admin-emoji-item">😐</div>
                                            <div onclick="insertAdminEmoji('😑')" class="admin-emoji-item">😑</div>
                                            <div onclick="insertAdminEmoji('😔')" class="admin-emoji-item">😔</div>
                                            <div onclick="insertAdminEmoji('😟')" class="admin-emoji-item">😟</div>
                                            <div onclick="insertAdminEmoji('😕')" class="admin-emoji-item">😕</div>
                                            <div onclick="insertAdminEmoji('🙁')" class="admin-emoji-item">🙁</div>
                                            <div onclick="insertAdminEmoji('😢')" class="admin-emoji-item">😢</div>
                                        </div>
                                    </div>
                                    <div>
                                        <div style="font-size: 12px; color: #999; margin-bottom: 8px;">手势表情</div>
                                        <div style="display: grid; grid-template-columns: repeat(8, 1fr); gap: 8px;">
                                            <div onclick="insertAdminEmoji('👋')" class="admin-emoji-item">👋</div>
                                            <div onclick="insertAdminEmoji('✌️')" class="admin-emoji-item">✌️</div>
                                            <div onclick="insertAdminEmoji('🤝')" class="admin-emoji-item">🤝</div>
                                            <div onclick="insertAdminEmoji('👏')" class="admin-emoji-item">👏</div>
                                            <div onclick="insertAdminEmoji('🙌')" class="admin-emoji-item">🙌</div>
                                            <div onclick="insertAdminEmoji('👍')" class="admin-emoji-item">👍</div>
                                            <div onclick="insertAdminEmoji('👎')" class="admin-emoji-item">👎</div>
                                            <div onclick="insertAdminEmoji('👌')" class="admin-emoji-item">👌</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 图片按钮 -->
                            <button onclick="uploadAdminImage()" class="admin-toolbar-btn" title="图片">
                                📷
                            </button>
                            
                            <!-- 隐藏的文件输入框 -->
                            <input type="file" id="adminImageInput" accept="image/*" style="display: none;">
                            
                            <!-- 文件按钮 -->
                            <button onclick="uploadAdminFile()" class="admin-toolbar-btn" title="文件">
                                📁
                            </button>
                            
                            <!-- 更多工具 -->
                            <button onclick="showAdminTools()" class="admin-toolbar-btn" title="更多工具">
                                💬
                            </button>
                        </div>
                        
                        <div class="layui-form">
                            <div class="layui-form-item">
                                <div style="position: relative; display: flex; align-items: center;">
                                    <textarea id="messageInput" placeholder="输入回复消息..." 
                                           class="layui-textarea" style="
                                               flex: 1; 
                                               border-radius: 0 0 4px 4px; 
                                               border-top: none;
                                               padding-right: 70px;
                                               height: 60px;
                                               resize: none;
                                               font-family: inherit;
                                               line-height: 1.4;
                                               overflow-y: auto;
                                           "></textarea>
                                    <button id="sendBtn" class="layui-btn layui-btn-primary layui-btn-sm" style="
                                        position: absolute;
                                        right: 8px;
                                        top: 50%;
                                        transform: translateY(-50%);
                                        border-radius: 4px;
                                        padding: 6px 12px;
                                        height: 32px;
                                        font-size: 12px;
                                        z-index: 10;
                                        display: flex;
                                        align-items: center;
                                        justify-content: center;
                                        line-height: 1;
                                    ">
                                        <i class="layui-icon layui-icon-release" style="margin-right: 4px;"></i>发送
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    
</div>

<!-- Socket.IO库 -->
<script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>
<!-- jQuery备用 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Layui -->
<script src="{{ url_for('admin.static', filename='system/component/layui/layui.js') }}"></script>

<script>
// 等待页面加载完成
$(document).ready(function() {
    // 使用jQuery作为$，创建简单的layer对象
    window.$ = jQuery;
    window.layer = {
        msg: function(text, options) {
            var icon = (options && options.icon === 2) ? '❌ ' : '✅ ';
            console.log(icon + text);
            
            // 创建简单的消息提示
            var msgDiv = $('<div style="position:fixed;top:20px;left:50%;transform:translateX(-50%);background:#333;color:white;padding:10px 20px;border-radius:4px;z-index:10000;">' + icon + text + '</div>');
            $('body').append(msgDiv);
            
            setTimeout(function() {
                msgDiv.fadeOut(function() {
                    msgDiv.remove();
                });
            }, 3000);
        },
        confirm: function(text, options, callback) {
            if (confirm(text) && typeof callback === 'function') {
                callback(0); // 传递index参数
            }
        },
        close: function(index) {
            // 简单实现，实际使用中可以忽略
        }
    };
    
    // 开始初始化聊天功能
    initChatSystem();
});

// 管理员工具栏全局函数

// 切换表情面板
function toggleAdminEmoji() {
    console.log('管理员表情面板切换');
    const emojiPanel = document.getElementById('adminEmojiPanel');
    if (!emojiPanel) {
        console.error('找不到管理员表情面板元素');
        return;
    }
    
    // 检查当前显示状态
    const currentDisplay = emojiPanel.style.display;
    const newDisplay = (currentDisplay === '' || currentDisplay === 'none') ? 'block' : 'none';
    emojiPanel.style.display = newDisplay;
    console.log('管理员表情面板显示状态:', newDisplay);
}

// 插入表情到管理员输入框
function insertAdminEmoji(emoji) {
    console.log('管理员插入表情:', emoji);
    const messageInput = document.getElementById('messageInput');
    if (!messageInput) {
        console.error('找不到管理员消息输入框');
        return;
    }
    
    const cursorPos = messageInput.selectionStart || messageInput.value.length;
    const textBefore = messageInput.value.substring(0, cursorPos);
    const textAfter = messageInput.value.substring(cursorPos);
    
    messageInput.value = textBefore + emoji + textAfter;
    messageInput.focus();
    
    // 设置光标位置
    const newCursorPos = cursorPos + emoji.length;
    messageInput.setSelectionRange(newCursorPos, newCursorPos);
    
    // 隐藏表情面板
    document.getElementById('adminEmojiPanel').style.display = 'none';
}

// 管理员上传图片
function uploadAdminImage() {
    const imageInput = document.getElementById('adminImageInput');
    if (imageInput) {
        imageInput.click();
    } else {
        console.error('找不到管理员图片上传输入框');
    }
}

// 管理员上传文件
function uploadAdminFile() {
    if (typeof layer !== 'undefined') {
        layer.msg('文件上传功能开发中...', {icon: 1});
    } else {
        alert('文件上传功能开发中...');
    }
}

// 显示更多工具
function showAdminTools() {
    if (typeof layer !== 'undefined') {
        layer.msg('更多工具功能开发中...', {icon: 1});
    } else {
        alert('更多工具功能开发中...');
    }
}

// 管理员语音通话功能
let adminCallState = 'idle'; // idle, incoming, connected
let currentCallSessionId = null;
let adminSocket = null; // 移到全局作用域
let adminRingtone = null; // 管理员铃声
let adminAudioContext = null; // 音频上下文
let adminLocalStream = null; // 管理员本地音频流
let adminRemoteAudio = null; // 管理员远程音频元素
let adminPeerConnection = null; // 管理员WebRTC连接
let adminIceCandidateQueue = []; // ICE候选队列
let incomingCallSessions = new Set(); // 待接听的通话会话集合
let activeCallSession = null; // 当前活跃的通话会话

// 管理员视频通话功能
let adminVideoCallState = 'idle'; // idle, incoming, connected
let currentVideoCallSessionId = null;
let adminVideoRingtone = null; // 管理员视频铃声
let adminVideoLocalStream = null; // 管理员本地视频流
let adminVideoRemoteVideo = null; // 管理员远程视频元素
let adminVideoLocalVideo = null; // 管理员本地视频元素
let adminVideoPeerConnection = null; // 管理员视频WebRTC连接
let adminVideoIceCandidateQueue = []; // 视频ICE候选队列
let incomingVideoCallSessions = new Set(); // 待接听的视频通话会话集合
let activeVideoCallSession = null; // 当前活跃的视频通话会话
let isVideoCall = false; // 区分语音通话和视频通话

// 管理员桌面共享功能
let adminDesktopShareState = 'idle'; // idle, incoming, connected
let currentDesktopShareSessionId = null;
let adminDesktopShareRingtone = null; // 管理员桌面共享铃声
let adminDesktopShareLocalStream = null; // 管理员本地桌面共享流
let adminDesktopShareRemoteVideo = null; // 管理员远程桌面共享视频元素
let adminDesktopSharePeerConnection = null; // 管理员桌面共享WebRTC连接
let adminDesktopShareIceCandidateQueue = []; // 桌面共享ICE候选队列
let incomingDesktopShareSessions = new Set(); // 待接听的桌面共享会话集合
let activeDesktopShareSession = null; // 当前活跃的桌面共享会话

// WebRTC配置
const adminRtcConfig = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' }
    ]
};

// 初始化管理员音频系统
function initAdminAudio() {
    try {
        adminAudioContext = new (window.AudioContext || window.webkitAudioContext)();
        console.log('管理员音频系统初始化成功');
        
        // 创建远程音频播放元素
        if (!adminRemoteAudio) {
            adminRemoteAudio = document.createElement('audio');
            adminRemoteAudio.autoplay = true;
            adminRemoteAudio.playsInline = true;
            document.body.appendChild(adminRemoteAudio);
            console.log('管理员远程音频元素已创建');
        }
    } catch (error) {
        console.error('管理员音频系统初始化失败:', error);
    }
}

// 获取管理员麦克风权限
async function getAdminMicrophone() {
    try {
        if (adminLocalStream) {
            console.log('管理员音频流已存在，无需重复获取');
            return adminLocalStream;
        }
        
        console.log('请求管理员麦克风权限...');
        adminLocalStream = await navigator.mediaDevices.getUserMedia({ 
            audio: {
                echoCancellation: true,
                noiseSuppression: true,
                autoGainControl: true
            }, 
            video: false 
        });
        console.log('管理员麦克风获取成功');
        return adminLocalStream;
    } catch (error) {
        console.error('获取管理员麦克风失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('无法访问麦克风，请检查权限设置', {icon: 2});
        }
        throw error;
    }
}

// 创建管理员WebRTC连接
async function createAdminPeerConnection() {
    try {
        console.log('创建管理员WebRTC连接...');
        adminPeerConnection = new RTCPeerConnection(adminRtcConfig);
        
        // 添加本地音频流
        const stream = await getAdminMicrophone();
        stream.getTracks().forEach(track => {
            adminPeerConnection.addTrack(track, stream);
            console.log('管理员音频轨道已添加到连接');
        });
        
        // 处理远程音频流
        adminPeerConnection.ontrack = function(event) {
            console.log('收到远程音频流');
            if (adminRemoteAudio && event.streams[0]) {
                adminRemoteAudio.srcObject = event.streams[0];
                console.log('远程音频流已设置到播放元素');
            }
        };
        
        // 处理ICE候选
        adminPeerConnection.onicecandidate = function(event) {
            if (event.candidate) {
                console.log('发送管理员ICE候选');
                adminSocket.emit('ice_candidate', {
                    session_id: currentCallSessionId,
                    candidate: event.candidate,
                    sender: 'admin'
                });
            }
        };
        
        // 连接状态变化
        adminPeerConnection.onconnectionstatechange = function() {
            console.log('管理员WebRTC连接状态:', adminPeerConnection.connectionState);
            if (adminPeerConnection.connectionState === 'connected') {
                console.log('管理员语音通话已建立');
            } else if (adminPeerConnection.connectionState === 'disconnected' || 
                      adminPeerConnection.connectionState === 'failed') {
                console.log('管理员语音通话连接断开');
                cleanupAdminCall();
            }
        };
        
        return adminPeerConnection;
    } catch (error) {
        console.error('创建管理员WebRTC连接失败:', error);
        throw error;
    }
}

// 清理管理员通话资源
function cleanupAdminCall() {
    console.log('清理管理员通话资源...');
    
    // 关闭WebRTC连接
    if (adminPeerConnection) {
        adminPeerConnection.close();
        adminPeerConnection = null;
        console.log('管理员WebRTC连接已关闭');
    }
    
    // 停止本地音频流
    if (adminLocalStream) {
        adminLocalStream.getTracks().forEach(track => {
            track.stop();
            console.log('管理员音频轨道已停止');
        });
        adminLocalStream = null;
    }
    
    // 清理远程音频
    if (adminRemoteAudio) {
        adminRemoteAudio.srcObject = null;
        console.log('管理员远程音频已清理');
    }
    
    // 清空ICE候选队列
    adminIceCandidateQueue = [];
    console.log('管理员ICE候选队列已清空');
    
    console.log('管理员通话资源清理完成');
}

// 播放管理员铃声
function playAdminRingtone() {
    if (!adminAudioContext) {
        initAdminAudio();
    }
    
    if (!adminAudioContext) {
        console.warn('音频系统不可用，无法播放铃声');
        return;
    }
    
    try {
        // 停止之前的铃声
        stopAdminRingtone();
        
        // 创建铃声 - 使用更舒缓的双音调
        const oscillator1 = adminAudioContext.createOscillator();
        const oscillator2 = adminAudioContext.createOscillator();
        const gainNode = adminAudioContext.createGain();
        
        // 设置音调频率 (更柔和的音调)
        oscillator1.frequency.setValueAtTime(800, adminAudioContext.currentTime); // 高音
        oscillator2.frequency.setValueAtTime(600, adminAudioContext.currentTime); // 低音
        
        // 设置音量
        gainNode.gain.setValueAtTime(0.3, adminAudioContext.currentTime);
        
        // 连接音频节点
        oscillator1.connect(gainNode);
        oscillator2.connect(gainNode);
        gainNode.connect(adminAudioContext.destination);
        
        // 启动铃声
        oscillator1.start();
        oscillator2.start();
        
        // 保存引用以便停止
        adminRingtone = {
            oscillator1: oscillator1,
            oscillator2: oscillator2,
            gainNode: gainNode
        };
        
        // 创建铃声模式 - 响铃1秒，停止0.5秒，循环
        setTimeout(() => {
            stopAdminRingtone();
            // 如果还在来电状态或回拨状态，继续播放铃声
            if (adminCallState === 'incoming' || adminCallState === 'calling') {
                setTimeout(() => {
                    if (adminCallState === 'incoming' || adminCallState === 'calling') {
                        playAdminRingtone();
                    }
                }, 500); // 停止0.5秒后继续
            }
        }, 1000); // 播放1秒
        
        console.log('管理员铃声开始播放');
    } catch (error) {
        console.error('播放管理员铃声失败:', error);
    }
}

// 停止管理员铃声
function stopAdminRingtone() {
    if (adminRingtone) {
        try {
            adminRingtone.oscillator1.stop();
            adminRingtone.oscillator2.stop();
            adminRingtone = null;
            console.log('管理员铃声已停止');
        } catch (error) {
            console.error('停止管理员铃声失败:', error);
            adminRingtone = null;
        }
    }
}

// 播放管理员视频铃声
function playAdminVideoRingtone() {
    if (!adminAudioContext) {
        initAdminAudio();
    }
    
    if (!adminAudioContext) {
        console.warn('音频系统不可用，无法播放视频铃声');
        return;
    }
    
    try {
        // 停止之前的铃声
        stopAdminVideoRingtone();
        
        // 创建视频铃声 - 使用不同的音调
        const oscillator1 = adminAudioContext.createOscillator();
        const oscillator2 = adminAudioContext.createOscillator();
        const gainNode = adminAudioContext.createGain();
        
        // 设置音调频率 (视频通话使用不同的音调)
        oscillator1.frequency.setValueAtTime(1000, adminAudioContext.currentTime); // 高音
        oscillator2.frequency.setValueAtTime(800, adminAudioContext.currentTime); // 中音
        
        // 设置音量
        gainNode.gain.setValueAtTime(0.3, adminAudioContext.currentTime);
        
        // 连接音频节点
        oscillator1.connect(gainNode);
        oscillator2.connect(gainNode);
        gainNode.connect(adminAudioContext.destination);
        
        // 启动铃声
        oscillator1.start();
        oscillator2.start();
        
        // 保存引用以便停止
        adminVideoRingtone = {
            oscillator1: oscillator1,
            oscillator2: oscillator2,
            gainNode: gainNode
        };
        
        // 创建铃声模式 - 响铃1秒，停止0.5秒，循环
        setTimeout(() => {
            stopAdminVideoRingtone();
            // 如果还在视频来电状态或回拨状态，继续播放铃声
            if (adminVideoCallState === 'incoming' || adminVideoCallState === 'calling') {
                setTimeout(() => {
                    if (adminVideoCallState === 'incoming' || adminVideoCallState === 'calling') {
                        playAdminVideoRingtone();
                    }
                }, 500); // 停止0.5秒后继续
            }
        }, 1000); // 播放1秒
        
        console.log('管理员视频铃声开始播放');
    } catch (error) {
        console.error('播放管理员视频铃声失败:', error);
    }
}

// 停止管理员视频铃声
function stopAdminVideoRingtone() {
    if (adminVideoRingtone) {
        try {
            adminVideoRingtone.oscillator1.stop();
            adminVideoRingtone.oscillator2.stop();
            adminVideoRingtone = null;
            console.log('管理员视频铃声已停止');
        } catch (error) {
            console.error('停止管理员视频铃声失败:', error);
            adminVideoRingtone = null;
        }
    }
}

// 处理管理员语音通话
function handleAdminVoiceCall() {
    if (adminCallState === 'incoming') {
        // 接听通话
        answerCall();
    } else if (adminCallState === 'connected') {
        // 结束通话
        endCall();
    }
}

// 处理管理员视频通话
function handleAdminVideoCall() {
    if (adminVideoCallState === 'incoming') {
        // 接听视频通话
        answerVideoCall();
    } else if (adminVideoCallState === 'connected') {
        // 结束视频通话
        endVideoCall();
    }
}

// 接听通话
async function answerCall() {
    if (!adminSocket || !adminSocket.connected || !currentCallSessionId) {
        if (typeof layer !== 'undefined') {
            layer.msg('无法接听通话', {icon: 2});
        } else {
            alert('无法接听通话');
        }
        return;
    }
    
    try {
        // 停止铃声
        stopAdminRingtone();
        
        // 设置活跃通话会话
        activeCallSession = currentCallSessionId;
        
        // 从待接听列表中移除当前会话
        incomingCallSessions.delete(currentCallSessionId);
        
        // 拒绝所有其他待接听的通话（改为发送队列状态）
        for (const sessionId of incomingCallSessions) {
            console.log('其他通话会话等待中:', sessionId);
            // 不再拒绝，保持在队列中等待
        }
        
        // 更新剩余队列用户的位置
        updateQueuePositions();
        
        // 清空待接听列表（当前通话变为活跃状态）
        // 注意：这里不清空，让其他用户继续排队
        
        console.log('管理员接听通话，活跃会话:', activeCallSession, '剩余队列:', Array.from(incomingCallSessions));
        
        // 创建WebRTC连接
        await createAdminPeerConnection();
        
        // 创建应答
        const offer = await adminPeerConnection.createOffer();
        await adminPeerConnection.setLocalDescription(offer);
        
        console.log('管理员创建应答，发送offer');
        
        // 发送接听信号和offer
        adminSocket.emit('admin_voice_call_answer', {
            session_id: currentCallSessionId,
            offer: offer
        });
        
        updateAdminCallButton('connected');
        if (typeof layer !== 'undefined') {
            layer.msg('通话已连接，正在建立音频连接...', {icon: 1});
        }
        
        // 发送接听通知到聊天框
        adminSocket.emit('voice_call_notification', {
            session_id: currentCallSessionId,
            type: 'answer',
            content: `📞 管理员接听通话 - ${new Date().toLocaleTimeString()}`,
            timestamp: new Date().toLocaleString()
        });
        
        // 更新会话列表显示
        updateSessionCallStatus();
        
    } catch (error) {
        console.error('接听通话失败:', error);
        if (typeof layer !== 'undefined') {
            layer.msg('接听通话失败: ' + error.message, {icon: 2});
        }
        resetAdminCallState();
    }
}

// 结束通话
function endCall() {
    if (!adminSocket || !adminSocket.connected || !currentCallSessionId) {
        return;
    }
    
    // 停止铃声
    stopAdminRingtone();
    
    // 清理WebRTC资源
    cleanupAdminCall();
    
    // 发送结束通话信号
    adminSocket.emit('admin_voice_call_end', {
        session_id: currentCallSessionId
    });
    
    // 发送结束通话通知到聊天框
    adminSocket.emit('voice_call_notification', {
        session_id: currentCallSessionId,
        type: 'end',
        content: `📞 管理员结束通话 - ${new Date().toLocaleTimeString()}`,
        timestamp: new Date().toLocaleString()
    });
    
    resetAdminCallState();
    if (typeof layer !== 'undefined') {
        layer.msg('通话已结束', {icon: 1});
    }
}

// 拒绝通话
function rejectCall() {
    if (!adminSocket || !adminSocket.connected) {
        return;
    }
    
    // 根据当前状态处理不同的拒绝逻辑
    if (adminCallState === 'calling') {
        // 取消语音回拨
        console.log('取消语音回拨:', currentCallSessionId);
        
        // 停止铃声
        stopAdminRingtone();
        
        // 发送取消回拨事件
        adminSocket.emit('admin_voice_call_cancel', {
            session_id: currentCallSessionId,
            reason: 'cancelled'
        });
        
        // 发送拒绝通话通知到聊天框
        adminSocket.emit('voice_call_notification', {
            session_id: currentCallSessionId,
            type: 'cancel_callback',
            content: `📞 管理员取消回拨 - ${new Date().toLocaleTimeString()}`,
            timestamp: new Date().toLocaleString()
        });
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('已取消语音回拨', {icon: 1});
        }
        
        // 重置状态
        resetAdminCallState();
        
    } else if (adminVideoCallState === 'calling') {
        // 取消视频回拨
        console.log('取消视频回拨:', currentVideoCallSessionId);
        
        // 停止视频铃声
        stopAdminVideoRingtone();
        
        // 发送取消视频回拨事件
        adminSocket.emit('admin_video_call_cancel', {
            session_id: currentVideoCallSessionId,
            reason: 'cancelled'
        });
        
        // 发送拒绝视频通话通知到聊天框
        adminSocket.emit('video_call_notification', {
            session_id: currentVideoCallSessionId,
            type: 'cancel_callback',
            content: `📹 管理员取消视频回拨 - ${new Date().toLocaleTimeString()}`,
            timestamp: new Date().toLocaleString()
        });
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('已取消视频回拨', {icon: 1});
        }
        
        // 重置状态
        resetAdminVideoCallState();
        
    } else if (adminCallState === 'incoming') {
        // 正常拒绝语音来电
        console.log('拒绝语音来电:', currentCallSessionId);
        
        // 停止铃声
        stopAdminRingtone();
        
        // 发送拒绝信号
        adminSocket.emit('admin_voice_call_reject', {
            session_id: currentCallSessionId
        });
        
        // 发送拒绝通话通知到聊天框
        adminSocket.emit('voice_call_notification', {
            session_id: currentCallSessionId,
            type: 'reject',
            content: `📞 管理员拒绝通话 - ${new Date().toLocaleTimeString()}`,
            timestamp: new Date().toLocaleString()
        });
        
        // 从待接听列表中移除当前会话
        incomingCallSessions.delete(currentCallSessionId);
        
        // 处理下一个待接听的通话
        processNextIncomingCall();
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('已拒绝语音通话', {icon: 1});
        }
        
    } else if (adminVideoCallState === 'incoming') {
        // 正常拒绝视频来电
        console.log('拒绝视频来电:', currentVideoCallSessionId);
        
        // 停止视频铃声
        stopAdminVideoRingtone();
        
        // 发送拒绝信号
        adminSocket.emit('admin_video_call_reject', {
            session_id: currentVideoCallSessionId
        });
        
        // 发送拒绝视频通话通知到聊天框
        adminSocket.emit('video_call_notification', {
            session_id: currentVideoCallSessionId,
            type: 'reject',
            content: `📹 管理员拒绝视频通话 - ${new Date().toLocaleTimeString()}`,
            timestamp: new Date().toLocaleString()
        });
        
        // 从待接听列表中移除当前会话
        incomingVideoCallSessions.delete(currentVideoCallSessionId);
        
        // 处理下一个待接听的视频通话
        processNextIncomingVideoCall();
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('已拒绝视频通话', {icon: 1});
        }
        
    } else if (adminDesktopShareState === 'incoming') {
        // 正常拒绝桌面共享来电
        console.log('拒绝桌面共享来电:', currentDesktopShareSessionId);
        
        // 停止桌面共享铃声
        stopAdminDesktopShareRingtone();
        
        // 发送拒绝信号
        adminSocket.emit('admin_desktop_share_reject', {
            session_id: currentDesktopShareSessionId
        });
        
        // 发送拒绝桌面共享通知到聊天框
        adminSocket.emit('desktop_share_notification', {
            session_id: currentDesktopShareSessionId,
            type: 'reject',
            content: `🖥️ 管理员拒绝桌面共享 - ${new Date().toLocaleTimeString()}`,
            timestamp: new Date().toLocaleString()
        });
        
        // 从待接听列表中移除当前会话
        incomingDesktopShareSessions.delete(currentDesktopShareSessionId);
        
        // 处理下一个待接听的桌面共享
        processNextIncomingDesktopShare();
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('已拒绝桌面共享', {icon: 1});
        }
        
    }
}

// 处理下一个待接听的通话
function processNextIncomingCall() {
    if (incomingCallSessions.size > 0) {
        // 获取下一个通话
        const nextSessionId = incomingCallSessions.values().next().value;
        currentCallSessionId = nextSessionId;
        
        updateAdminCallButton('incoming');
        playAdminRingtone();
        
        console.log('切换到下一个通话:', nextSessionId, '还有', incomingCallSessions.size - 1, '个待接听');
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg(`切换到下一个通话，还有 ${incomingCallSessions.size - 1} 个待接听`, {
                icon: 1,
                time: 2000
            });
        }
        
        // 更新所有排队用户的位置
        updateQueuePositions();
    } else {
        resetAdminCallState();
    }
    
    updateSessionCallStatus();
}

// 更新队列中所有用户的位置
function updateQueuePositions() {
    console.log('更新队列位置，当前队列:', Array.from(incomingCallSessions));
    
    let position = 1;
    for (const sessionId of incomingCallSessions) {
        if (sessionId !== currentCallSessionId) {
            // 发送更新的队列位置给用户
            adminSocket.emit('voice_call_queue_status', {
                session_id: sessionId,
                status: 'queued',
                position: position,
                message: position === 1 ? 
                    '您是下一位，请保持等待...' : 
                    `当前有 ${position - 1} 人在您前面排队，请稍候...`
            });
            position++;
        }
    }
}

// 更新管理员通话按钮状态
function updateAdminCallButton(state) {
    const callBtn = document.getElementById('adminVoiceCallBtn');
    const callBtnText = document.getElementById('adminCallBtnText');
    const rejectBtn = document.getElementById('adminRejectCallBtn');
    
    if (!callBtn || !callBtnText || !rejectBtn) return;
    
    adminCallState = state;
    
    switch (state) {
        case 'idle':
            callBtn.style.display = 'none';
            rejectBtn.style.display = 'none';
            break;
        case 'incoming':
            callBtn.style.display = 'inline-block';
            callBtn.style.background = '#1e88e5';
            callBtnText.textContent = '接听通话';
            rejectBtn.style.display = 'inline-block';
            break;
        case 'calling':
            callBtn.style.display = 'inline-block';
            callBtn.style.background = '#ff9800';
            callBtnText.textContent = '回拨中...';
            rejectBtn.style.display = 'inline-block';
            rejectBtn.innerHTML = '<i class="layui-icon layui-icon-close"></i> 取消回拨';
            break;
        case 'connected':
            callBtn.style.display = 'inline-block';
            callBtn.style.background = '#f44336';
            callBtnText.textContent = '结束通话';
            rejectBtn.style.display = 'none'; // 通话结束后隐藏拒绝按钮
            break;
    }
}

// 重置管理员通话状态
function resetAdminCallState() {
    adminCallState = 'idle';
    activeCallSession = null;
    stopAdminRingtone(); // 确保铃声停止
    cleanupAdminCall(); // 清理WebRTC资源
    
    // 如果有排队的通话，处理下一个
    if (incomingCallSessions.size > 0) {
        console.log('活跃通话结束，处理队列中的下一个通话');
        processNextIncomingCall();
    } else {
        // 没有排队的通话，完全重置
        currentCallSessionId = null;
        updateAdminCallButton('idle');
        updateSessionCallStatus();
    }
}

// 回拨用户
function callbackUser(sessionId) {
    console.log('管理员回拨用户，会话ID:', sessionId);
    
    if (!adminSocket || !adminSocket.connected) {
        console.log('管理员端未连接，无法回拨');
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('连接已断开，无法回拨', {icon: 2});
        }
        return;
    }
    
    try {
        // 设置管理员为回拨状态
        adminCallState = 'calling';
        currentCallSessionId = sessionId;
        updateAdminCallButton('calling');
        
        // 播放回拨铃声
        playAdminRingtone();
        console.log('开始播放管理员回拨铃声');
        
        // 发送回拨请求
        adminSocket.emit('admin_voice_call_callback', {
            session_id: sessionId,
            type: 'callback_request'
        });
        
        console.log('管理员回拨请求已发送:', sessionId);
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('正在回拨用户，请等待用户接听...', {icon: 1, time: 3000});
        }
        
    } catch (error) {
        console.error('回拨用户失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('回拨失败', {icon: 2});
        }
    }
}

// 处理用户接听
async function handleUserAccepted(sessionId) {
    console.log('处理用户接听，会话ID:', sessionId);
    
    try {
        // 设置当前会话ID
        currentCallSessionId = sessionId;
        
        // 创建WebRTC连接
        await createAdminPeerConnection();
        
        // 创建offer
        const offer = await adminPeerConnection.createOffer();
        await adminPeerConnection.setLocalDescription(offer);
        
        console.log('管理员创建offer成功，发送给用户');
        
        // 发送offer给用户
        adminSocket.emit('admin_voice_call_answer', {
            session_id: sessionId,
            offer: offer
        });
        
        // 更新按钮状态
        adminCallState = 'connected';
        updateAdminCallButton('connected');
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('用户已接听，正在建立音频连接...', {icon: 1});
        }
        
        console.log('WebRTC offer已发送给用户');
        
    } catch (error) {
        console.error('处理用户接听失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('建立音频连接失败: ' + error.message, {icon: 2});
        }
        resetAdminCallState();
    }
}

// 处理用户接听视频通话
async function handleUserVideoAccepted(sessionId) {
    console.log('处理用户接听视频通话，会话ID:', sessionId);
    
    try {
        // 设置当前会话ID
        currentVideoCallSessionId = sessionId;
        
        // 初始化视频元素
        initAdminVideoElements();
        
        // 获取摄像头权限并显示本地视频
        const stream = await getAdminVideo();
        if (adminVideoLocalVideo && stream) {
            adminVideoLocalVideo.srcObject = stream;
            console.log('管理员本地视频流已设置');
            
            // 确保本地视频开始播放
            adminVideoLocalVideo.play().then(() => {
                console.log('管理员本地视频开始播放');
            }).catch(error => {
                console.error('管理员本地视频播放失败:', error);
            });
        } else {
            console.error('管理员本地视频元素或流不存在');
        }
        
        // 创建视频WebRTC连接
        await createAdminVideoPeerConnection();
        
        // 创建offer
        const offer = await adminVideoPeerConnection.createOffer();
        await adminVideoPeerConnection.setLocalDescription(offer);
        
        console.log('管理员创建视频offer成功，发送给用户');
        
        // 发送offer给用户
        adminSocket.emit('admin_video_call_answer', {
            session_id: sessionId,
            offer: offer
        });
        
        // 更新按钮状态
        adminVideoCallState = 'connected';
        updateAdminVideoCallButton('connected');
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('用户已接听视频通话，正在建立视频连接...', {icon: 1});
        }
        
        console.log('视频WebRTC offer已发送给用户');
        
    } catch (error) {
        console.error('处理用户接听视频通话失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('建立视频连接失败: ' + error.message, {icon: 2});
        }
        resetAdminVideoCallState();
    }
}

function initChatSystem() {
    let activeSessions = [];
    let currentSessionId = null;
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 5;
    let sessionsWithNewMessages = new Set(); // 跟踪有新消息的会话
    let userHasInteracted = false; // 用户是否已经与页面交互过
    
    // 添加新消息提醒
    function addNewMessageNotification(sessionId) {
        if (sessionId !== currentSessionId) {
            sessionsWithNewMessages.add(sessionId);
            console.log(`会话 ${sessionId} 有新消息提醒`);
            // 重新渲染会话列表以显示提醒
            renderSessionsList();
        }
    }
    
    // 清除新消息提醒
    function clearNewMessageNotification(sessionId) {
        sessionsWithNewMessages.delete(sessionId);
        console.log(`清除会话 ${sessionId} 的新消息提醒`);
        // 重新渲染会话列表以隐藏提醒
        renderSessionsList();
    }
    
    // 更新连接状态
    function updateConnectionStatus(status, message) {
        const statusElement = document.getElementById('connectionStatus');
        if (!statusElement) return;
        
        switch (status) {
            case 'connected':
                statusElement.style.background = '#5FB878';
                statusElement.innerHTML = '<i class="layui-icon layui-icon-ok"></i> 连接状态: 已连接';
                break;
            case 'connecting':
                statusElement.style.background = '#FFB800';
                statusElement.innerHTML = '<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 连接状态: 连接中...';
                break;
            case 'disconnected':
                statusElement.style.background = '#FF5722';
                statusElement.innerHTML = '<i class="layui-icon layui-icon-close"></i> 连接状态: 断开';
                break;
            case 'error':
                statusElement.style.background = '#FF5722';
                statusElement.innerHTML = '<i class="layui-icon layui-icon-close"></i> 连接状态: 错误';
                break;
        }
        
        if (message) {
            console.log('连接状态:', status, message);
        }
    }
    
    // 初始化WebSocket连接
    function initAdminSocket() {
        try {
            updateConnectionStatus('connecting');
            
            adminSocket = io('/admin/chat', {
                transports: ['polling', 'websocket'],
                timeout: 20000,
                reconnection: true,
                reconnectionAttempts: maxReconnectAttempts,
                reconnectionDelay: 1000,
                forceNew: true,
                secure: false
            });
            
            // 连接成功
            adminSocket.on('connect', function() {
                console.log('管理员Socket连接成功');
                updateConnectionStatus('connected');
                reconnectAttempts = 0;
                
                // 加入管理员房间
                console.log('发送加入管理员房间请求...');
                adminSocket.emit('join_admin_room');
                
                // 延迟获取活跃会话，确保加入房间完成
                setTimeout(function() {
                    console.log('延迟获取活跃会话...');
                    getActiveSessions();
                }, 500);
            });
            
            // 连接断开
            adminSocket.on('disconnect', function(reason) {
                console.log('管理员Socket连接断开:', reason);
                updateConnectionStatus('disconnected');
            });
            
            // 连接错误
            adminSocket.on('connect_error', function(error) {
                console.error('管理员Socket连接错误:', error);
                updateConnectionStatus('error');
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg('连接服务器失败', {icon: 2});
                }
            });
            
            // 重连尝试
            adminSocket.on('reconnect_attempt', function(attemptNumber) {
                reconnectAttempts = attemptNumber;
                updateConnectionStatus('connecting', `重连尝试 ${attemptNumber}`);
            });
            
            // 获取活跃会话响应
            adminSocket.on('active_sessions', function(data) {
                console.log('收到活跃会话:', data);
                activeSessions = data.sessions || [];
                renderSessionsList();
            });
            
            // 加入管理员房间成功
            adminSocket.on('joined_admin_room', function(data) {
                console.log('成功加入管理员房间:', data);
                // 加入房间成功后立即获取活跃会话
                getActiveSessions();
            });
            
            // 新用户消息
            adminSocket.on('new_user_message', function(data) {
                console.log('收到新用户消息:', data);
                
                // 播放提示音
                playMessageSound();
                
                // 如果不是当前监控的会话，添加新消息提醒
                if (data.session_id !== currentSessionId) {
                    addNewMessageNotification(data.session_id);
                } else {
                    // 如果是当前会话，直接显示消息
                    addMessageToChat(data.content, data.sender_type, data.create_time, data.message_type, data.image_data);
                }
                
                // 更新会话列表
                getActiveSessions();
            });
            
            // 消息发送成功
            adminSocket.on('message_sent', function(data) {
                console.log('消息发送成功:', data);
                addMessageToChat(data.content, 'admin', data.create_time, data.message_type, data.image_data);
                document.getElementById('messageInput').value = '';
            });
            
            // 会话关闭成功
            adminSocket.on('session_closed', function(data) {
                console.log('会话关闭:', data);
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg(data.msg || '会话已关闭', {icon: 1});
                }
                
                // 刷新会话列表
                getActiveSessions();
                
                // 如果关闭的是当前会话，清空聊天区域
                if (data.session_id === currentSessionId) {
                    currentSessionId = null;
                    document.getElementById('chatTitle').innerHTML = '<i class="layui-icon layui-icon-chat"></i> 选择一个会话开始聊天';
                    document.getElementById('chatMessages').innerHTML = '<div style="text-align: center; color: #999; padding: 40px;"><i class="layui-icon layui-icon-chat" style="font-size: 48px; color: #ddd;"></i><div style="margin-top: 10px;">请选择左侧会话开始聊天</div></div>';
                    document.getElementById('chatInputArea').style.display = 'none';
                    document.getElementById('closeSessionBtn').style.display = 'none';
                }
            });
            
            // 错误处理
            adminSocket.on('error', function(data) {
                console.error('Socket错误:', data);
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg('错误: ' + (data.msg || '未知错误'), {icon: 2});
                }
            });
            
            // 用户断开连接
            adminSocket.on('user_disconnected', function(data) {
                console.log('用户断开连接:', data);
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg('用户已断开连接', {icon: 1});
                }
                
                // 刷新会话列表以更新状态
                getActiveSessions();
            });
            
            // 语音通话事件处理
            
            // 收到用户语音通话请求
            adminSocket.on('voice_call_request', function(data) {
                console.log('收到用户语音通话请求:', data);

                // 检查是否已有活跃通话
                if (activeCallSession && activeCallSession !== data.session_id) {
                    console.log('已有活跃通话，将新请求加入队列:', data.session_id);
                    
                    // 不要拒绝，而是加入队列并告知用户排队状态
                    incomingCallSessions.add(data.session_id);
                    
                    // 发送队列状态给用户
                    adminSocket.emit('voice_call_queue_status', {
                        session_id: data.session_id,
                        status: 'queued',
                        position: incomingCallSessions.size,
                        message: `当前管理员正在通话中，您排在第 ${incomingCallSessions.size} 位，请稍候...`
                    });
                    
                    // 更新会话状态显示
                    updateSessionCallStatus();
                    return;
                }

                // 检查是否已经在待接听列表中
                if (incomingCallSessions.has(data.session_id)) {
                    console.log('通话请求已存在:', data.session_id);
                    return;
                }

                // 添加到待接听列表
                incomingCallSessions.add(data.session_id);
                console.log('待接听通话列表:', Array.from(incomingCallSessions));

                // 如果是第一个通话请求，设置为当前会话并播放铃声
                if (incomingCallSessions.size === 1) {
                    currentCallSessionId = data.session_id;
                    updateAdminCallButton('incoming');
                    playAdminRingtone();
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        layer.msg('收到用户语音通话请求，点击接听按钮接听', {
                            icon: 1,
                            time: 3000 // 3秒后自动关闭
                        });
                    } else {
                        console.log('收到用户语音通话请求，请点击接听按钮');
                    }
                } else {
                    // 多个通话排队等待
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        layer.msg(`收到新的通话请求，当前排队: ${incomingCallSessions.size}个`, {
                            icon: 1,
                            time: 2000
                        });
                    }
                    
                    // 发送队列状态给用户
                    adminSocket.emit('voice_call_queue_status', {
                        session_id: data.session_id,
                        status: 'queued',
                        position: incomingCallSessions.size,
                        message: `当前有 ${incomingCallSessions.size - 1} 人在您前面排队，请稍候...`
                    });
                }
                
                updateSessionCallStatus(); // 更新会话列表显示
            });
            
            // 用户取消通话
            adminSocket.on('voice_call_cancelled', function(data) {
                console.log('通话被取消:', data);
                
                // 立即停止铃声
                stopAdminRingtone();
                
                // 如果是当前正在处理的通话
                if (data.session_id === currentCallSessionId) {
                    console.log('当前通话被取消，重置状态');
                    
                    // 从待接听列表中移除
                    incomingCallSessions.delete(data.session_id);
                    
                    // 处理下一个待接听的通话
                    processNextIncomingCall();
                    
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        const message = data.from === 'user' ? '用户已取消通话' : '通话已取消';
                        layer.msg(message, {icon: 1, time: 2000});
                    }
                } else {
                    // 如果是队列中的其他通话
                    incomingCallSessions.delete(data.session_id);
                    console.log('队列中的通话被取消:', data.session_id);
                }
                
                // 更新会话状态显示
                updateSessionCallStatus();
            });
            
            // 用户结束通话
            adminSocket.on('voice_call_ended', function(data) {
                console.log('用户结束通话:', data);
                
                // 立即停止铃声
                stopAdminRingtone();
                
                // 从待接听列表中移除
                incomingCallSessions.delete(data.session_id);
                
                // 如果结束的是当前活跃通话
                if (activeCallSession === data.session_id) {
                    resetAdminCallState();
                } else if (currentCallSessionId === data.session_id) {
                    // 如果结束的是当前待接听的通话
                    processNextIncomingCall();
                }
                
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg('通话已结束', {icon: 1});
                }
                
                // 更新会话列表显示
                updateSessionCallStatus();
            });
            
            // 收到未接来电通知
            adminSocket.on('voice_call_missed', function(data) {
                console.log('收到未接来电通知:', data);
                
                // 不再弹窗，系统消息已经在聊天框中显示
                // 用户可以点击系统消息进行回拨
                console.log('用户呼叫超时，可点击系统消息进行回拨:', data.session_id);
                
                // 更新会话列表
                getActiveSessions();
            });
            
            // 用户接听通话
            adminSocket.on('voice_call_accepted', function(data) {
                console.log('用户接听通话:', data);
                
                // 停止回拨铃声
                stopAdminRingtone();
                console.log('用户接听，停止管理员端铃声');
                
                if (data.session_id) {
                    // 用户接听了，现在管理员创建WebRTC连接
                    handleUserAccepted(data.session_id);
                }
            });
            
            // 用户拒绝通话
            adminSocket.on('voice_call_rejected', function(data) {
                console.log('用户拒绝通话:', data);
                
                // 停止回拨铃声
                stopAdminRingtone();
                console.log('用户拒绝，停止管理员端铃声');
                
                // 重置管理员状态
                if (data.session_id === currentCallSessionId) {
                    resetAdminCallState();
                    
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        layer.msg('用户拒绝了回拨', {icon: 2, time: 2000});
                    }
                }
            });
            
            // 语音通话通知（在聊天框显示）
            adminSocket.on('voice_call_notification', function(data) {
                console.log('收到语音通话通知:', data);
                
                // 在对应会话的聊天框中添加系统消息
                if (data.session_id && currentSessionId === data.session_id) {
                    // 使用统一的addMessageToChat函数显示系统消息
                    addMessageToChat(data.content, 'system', data.timestamp, 'system', null);
                }
                
                // 更新会话列表
                getActiveSessions();
            });
            
            // 处理ICE候选
            adminSocket.on('ice_candidate', function(data) {
                console.log('收到ICE候选:', data);
                if (adminPeerConnection && data.candidate && data.sender !== 'admin') {
                    // 检查是否已设置远程描述
                    if (adminPeerConnection.remoteDescription) {
                        // 远程描述已设置，直接添加ICE候选
                        adminPeerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                            .then(() => {
                                console.log('管理员ICE候选添加成功');
                            })
                            .catch(error => {
                                console.error('管理员ICE候选添加失败:', error);
                            });
                    } else {
                        // 远程描述未设置，将ICE候选加入队列
                        console.log('远程描述未设置，ICE候选加入队列');
                        adminIceCandidateQueue.push(data.candidate);
                    }
                }
            });
            
            // 处理用户的WebRTC应答
            adminSocket.on('voice_call_answer', function(data) {
                console.log('收到用户的WebRTC应答:', data);
                if (adminPeerConnection && data.answer) {
                    adminPeerConnection.setRemoteDescription(new RTCSessionDescription(data.answer))
                        .then(() => {
                            console.log('管理员设置远程描述成功');
                            
                            // 处理队列中的ICE候选
                            console.log('处理队列中的ICE候选，队列长度:', adminIceCandidateQueue.length);
                            while (adminIceCandidateQueue.length > 0) {
                                const candidate = adminIceCandidateQueue.shift();
                                adminPeerConnection.addIceCandidate(new RTCIceCandidate(candidate))
                                    .then(() => {
                                        console.log('队列中的管理员ICE候选添加成功');
                                    })
                                    .catch(error => {
                                        console.error('队列中的管理员ICE候选添加失败:', error);
                                    });
                            }
                        })
                        .catch(error => {
                            console.error('管理员设置远程描述失败:', error);
                        });
                }
            });
            
            // 视频通话事件处理
            
            // 收到用户视频通话请求
            adminSocket.on('video_call_request', function(data) {
                console.log('收到用户视频通话请求:', data);

                // 检查是否已有活跃视频通话
                if (activeVideoCallSession && activeVideoCallSession !== data.session_id) {
                    console.log('已有活跃视频通话，将新请求加入队列:', data.session_id);
                    
                    // 不要拒绝，而是加入队列并告知用户排队状态
                    incomingVideoCallSessions.add(data.session_id);
                    
                    // 发送队列状态给用户
                    adminSocket.emit('video_call_queue_status', {
                        session_id: data.session_id,
                        status: 'queued',
                        position: incomingVideoCallSessions.size,
                        message: `当前管理员正在视频通话中，您排在第 ${incomingVideoCallSessions.size} 位，请稍候...`
                    });
                    
                    // 更新会话状态显示
                    updateSessionCallStatus();
                    return;
                }

                // 检查是否已经在待接听列表中
                if (incomingVideoCallSessions.has(data.session_id)) {
                    console.log('视频通话请求已存在:', data.session_id);
                    return;
                }

                // 添加到待接听列表
                incomingVideoCallSessions.add(data.session_id);
                console.log('待接听视频通话列表:', Array.from(incomingVideoCallSessions));

                // 如果是第一个视频通话请求，设置为当前会话并播放铃声
                if (incomingVideoCallSessions.size === 1) {
                    currentVideoCallSessionId = data.session_id;
                    updateAdminVideoCallButton('incoming');
                    playAdminVideoRingtone();
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        layer.msg('收到用户视频通话请求，点击接听按钮接听', {
                            icon: 1,
                            time: 3000 // 3秒后自动关闭
                        });
                    } else {
                        console.log('收到用户视频通话请求，请点击接听按钮');
                    }
                } else {
                    // 多个视频通话排队等待
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        layer.msg(`收到新的视频通话请求，当前排队: ${incomingVideoCallSessions.size}个`, {
                            icon: 1,
                            time: 2000
                        });
                    }
                    
                    // 发送队列状态给用户
                    adminSocket.emit('video_call_queue_status', {
                        session_id: data.session_id,
                        status: 'queued',
                        position: incomingVideoCallSessions.size,
                        message: `当前有 ${incomingVideoCallSessions.size - 1} 人在您前面排队，请稍候...`
                    });
                }
                
                updateSessionCallStatus(); // 更新会话列表显示
            });
            
            // 用户取消视频通话
            adminSocket.on('video_call_cancelled', function(data) {
                console.log('视频通话被取消:', data);
                
                // 立即停止视频铃声
                stopAdminVideoRingtone();
                
                // 如果是当前正在处理的视频通话
                if (data.session_id === currentVideoCallSessionId) {
                    console.log('当前视频通话被取消，重置状态');
                    
                    // 从待接听列表中移除
                    incomingVideoCallSessions.delete(data.session_id);
                    
                    // 处理下一个待接听的视频通话
                    processNextIncomingVideoCall();
                    
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        const message = data.from === 'user' ? '用户已取消视频通话' : '视频通话已取消';
                        layer.msg(message, {icon: 1, time: 2000});
                    }
                } else {
                    // 如果是队列中的其他视频通话
                    incomingVideoCallSessions.delete(data.session_id);
                    console.log('队列中的视频通话被取消:', data.session_id);
                }
                
                // 更新会话状态显示
                updateSessionCallStatus();
            });
            
            // 用户结束视频通话
            adminSocket.on('video_call_ended', function(data) {
                console.log('收到用户结束视频通话事件:', data);
                
                // 立即停止视频铃声
                stopAdminVideoRingtone();
                console.log('已停止管理员视频铃声');
                
                // 从待接听列表中移除
                incomingVideoCallSessions.delete(data.session_id);
                console.log('已从待接听列表中移除会话:', data.session_id);
                
                // 如果结束的是当前活跃视频通话
                if (activeVideoCallSession === data.session_id) {
                    console.log('结束的是当前活跃视频通话，重置状态');
                    resetAdminVideoCallState();
                } else if (currentVideoCallSessionId === data.session_id) {
                    // 如果结束的是当前待接听的视频通话
                    console.log('结束的是当前待接听的视频通话，处理下一个');
                    processNextIncomingVideoCall();
                } else {
                    console.log('结束的不是当前处理的视频通话，仅清理状态');
                    // 确保状态被重置
                    if (adminVideoCallState !== 'idle') {
                        resetAdminVideoCallState();
                    }
                }
                
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg('视频通话已结束', {icon: 1});
                }
                
                // 更新会话列表显示
                updateSessionCallStatus();
                console.log('视频通话结束处理完成');
            });
            
            // 收到未接视频来电通知
            adminSocket.on('video_call_missed', function(data) {
                console.log('收到未接视频来电通知:', data);
                
                // 不再弹窗，系统消息已经在聊天框中显示
                // 用户可以点击系统消息进行回拨
                console.log('用户视频呼叫超时，可点击系统消息进行回拨:', data.session_id);
                
                // 更新会话列表
                getActiveSessions();
            });
            
            // 用户接听视频通话
            adminSocket.on('video_call_accepted', function(data) {
                console.log('用户接听视频通话:', data);
                
                // 停止回拨视频铃声
                stopAdminVideoRingtone();
                console.log('用户接听视频通话，停止管理员端视频铃声');
                
                if (data.session_id) {
                    // 用户接听了，现在管理员创建视频WebRTC连接
                    handleUserVideoAccepted(data.session_id);
                }
            });
            
            // 用户拒绝视频通话
            adminSocket.on('video_call_rejected', function(data) {
                console.log('用户拒绝视频通话:', data);
                
                // 停止回拨视频铃声
                stopAdminVideoRingtone();
                console.log('用户拒绝视频通话，停止管理员端视频铃声');
                
                // 重置管理员状态
                if (data.session_id === currentVideoCallSessionId) {
                    resetAdminVideoCallState();
                    
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        layer.msg('用户拒绝了视频回拨', {icon: 2, time: 2000});
                    }
                }
            });
            
            // 视频通话通知（在聊天框显示）
            adminSocket.on('video_call_notification', function(data) {
                console.log('收到视频通话通知:', data);
                
                // 在对应会话的聊天框中添加系统消息
                if (data.session_id && currentSessionId === data.session_id) {
                    // 使用统一的addMessageToChat函数显示系统消息
                    addMessageToChat(data.content, 'system', data.timestamp, 'system', null);
                }
                
                // 更新会话列表
                getActiveSessions();
            });
            
            // 处理视频ICE候选
            adminSocket.on('video_ice_candidate', function(data) {
                console.log('收到视频ICE候选:', data);
                if (adminVideoPeerConnection && data.candidate && data.sender !== 'admin') {
                    // 检查是否已设置远程描述
                    if (adminVideoPeerConnection.remoteDescription) {
                        // 远程描述已设置，直接添加ICE候选
                        adminVideoPeerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                            .then(() => {
                                console.log('管理员视频ICE候选添加成功');
                            })
                            .catch(error => {
                                console.error('管理员视频ICE候选添加失败:', error);
                            });
                    } else {
                        // 远程描述未设置，将ICE候选加入队列
                        console.log('视频远程描述未设置，ICE候选加入队列');
                        adminVideoIceCandidateQueue.push(data.candidate);
                    }
                }
            });
            
            // 处理用户的视频WebRTC应答
            adminSocket.on('video_call_answer', function(data) {
                console.log('收到用户的视频WebRTC应答:', data);
                if (adminVideoPeerConnection && data.answer) {
                    adminVideoPeerConnection.setRemoteDescription(new RTCSessionDescription(data.answer))
                        .then(() => {
                            console.log('管理员设置视频远程描述成功');
                            
                            // 处理队列中的ICE候选
                            console.log('处理队列中的视频ICE候选，队列长度:', adminVideoIceCandidateQueue.length);
                            while (adminVideoIceCandidateQueue.length > 0) {
                                const candidate = adminVideoIceCandidateQueue.shift();
                                adminVideoPeerConnection.addIceCandidate(new RTCIceCandidate(candidate))
                                    .then(() => {
                                        console.log('队列中的管理员视频ICE候选添加成功');
                                    })
                                    .catch(error => {
                                        console.error('队列中的管理员视频ICE候选添加失败:', error);
                                    });
                            }
                        })
                        .catch(error => {
                            console.error('管理员设置视频远程描述失败:', error);
                        });
                }
            });
            
            // 桌面共享事件处理
            
            // 收到用户桌面共享请求
            adminSocket.on('desktop_share_incoming', function(data) {
                console.log('收到用户桌面共享请求:', data);

                // 检查是否已有活跃桌面共享
                if (activeDesktopShareSession && activeDesktopShareSession !== data.session_id) {
                    console.log('已有活跃桌面共享，将新请求加入队列:', data.session_id);
                    
                    // 不要拒绝，而是加入队列并告知用户排队状态
                    incomingDesktopShareSessions.add(data.session_id);
                    
                    // 发送队列状态给用户
                    adminSocket.emit('desktop_share_queue_status', {
                        session_id: data.session_id,
                        status: 'queued',
                        position: incomingDesktopShareSessions.size,
                        message: `当前管理员正在桌面共享中，您排在第 ${incomingDesktopShareSessions.size} 位，请稍候...`
                    });
                    
                    // 更新会话状态显示
                    updateSessionCallStatus();
                    return;
                }

                // 检查是否已经在待接听列表中
                if (incomingDesktopShareSessions.has(data.session_id)) {
                    console.log('桌面共享请求已存在:', data.session_id);
                    return;
                }

                // 添加到待接听列表
                incomingDesktopShareSessions.add(data.session_id);
                console.log('待接听桌面共享列表:', Array.from(incomingDesktopShareSessions));

                // 如果是第一个桌面共享请求，设置为当前会话并播放铃声
                if (incomingDesktopShareSessions.size === 1) {
                    currentDesktopShareSessionId = data.session_id;
                    updateAdminDesktopShareButton('incoming');
                    playAdminDesktopShareRingtone();
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        layer.msg('收到用户桌面共享请求，点击接听按钮接听', {
                            icon: 1,
                            time: 3000 // 3秒后自动关闭
                        });
                    } else {
                        console.log('收到用户桌面共享请求，请点击接听按钮');
                    }
                } else {
                    // 多个桌面共享排队等待
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        layer.msg(`收到新的桌面共享请求，当前排队: ${incomingDesktopShareSessions.size}个`, {
                            icon: 1,
                            time: 2000
                        });
                    }
                    
                    // 发送队列状态给用户
                    adminSocket.emit('desktop_share_queue_status', {
                        session_id: data.session_id,
                        status: 'queued',
                        position: incomingDesktopShareSessions.size,
                        message: `当前有 ${incomingDesktopShareSessions.size - 1} 人在您前面排队，请稍候...`
                    });
                }
                
                updateSessionCallStatus(); // 更新会话列表显示
            });
            
            // 用户取消桌面共享
            adminSocket.on('desktop_share_cancelled', function(data) {
                console.log('桌面共享取消:', data);
                
                // 防止重复处理
                if (adminDesktopShareState === 'idle') {
                    console.log('桌面共享状态已为空闲，跳过取消处理');
                    return;
                }
                
                // 立即停止桌面共享铃声
                stopAdminDesktopShareRingtone();
                
                // 如果是当前活跃的桌面共享
                if (data.session_id === activeDesktopShareSession) {
                    activeDesktopShareSession = null;
                    console.log('当前活跃桌面共享被取消');
                    
                    // 清理桌面共享资源
                    closeDesktopSharePopup();
                    
                    // 清理桌面共享流
                    if (adminDesktopShareLocalStream) {
                        adminDesktopShareLocalStream.getTracks().forEach(track => track.stop());
                        adminDesktopShareLocalStream = null;
                    }
                    
                    // 关闭桌面共享WebRTC连接
                    if (adminDesktopSharePeerConnection) {
                        adminDesktopSharePeerConnection.close();
                        adminDesktopSharePeerConnection = null;
                    }
                    
                    // 清空桌面共享ICE候选队列
                    adminDesktopShareIceCandidateQueue = [];
                    
                    // 重置状态
                    adminDesktopShareState = 'idle';
                    activeDesktopShareSession = null;
                    currentDesktopShareSessionId = null;
                    
                    // 从待接听列表中移除
                    incomingDesktopShareSessions.delete(data.session_id);
                    
                    // 处理下一个待接听的桌面共享（如果有的话）
                    if (incomingDesktopShareSessions.size > 0) {
                        processNextIncomingDesktopShare();
                    } else {
                        // 没有排队的桌面共享，直接更新状态
                        updateAdminDesktopShareButton('idle');
                    }
                    
                    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                        const message = data.from === 'user' ? '用户已取消桌面共享' : '桌面共享已取消';
                        layer.msg(message, {icon: 1, time: 2000});
                    }
                } else {
                    // 如果是队列中的其他桌面共享
                    incomingDesktopShareSessions.delete(data.session_id);
                    console.log('队列中的桌面共享被取消:', data.session_id);
                }
                
                // 更新会话状态显示
                updateSessionCallStatus();
            });
            
            // 桌面共享结束
            adminSocket.on('desktop_share_ended', function(data) {
                console.log('桌面共享结束:', data);
                
                // 防止重复处理
                if (adminDesktopShareState === 'idle') {
                    console.log('桌面共享状态已为空闲，跳过结束处理');
                    return;
                }
                
                // 立即停止桌面共享铃声
                stopAdminDesktopShareRingtone();
                
                // 关闭桌面共享弹窗
                closeDesktopSharePopup();
                
                // 清理桌面共享流
                if (adminDesktopShareLocalStream) {
                    adminDesktopShareLocalStream.getTracks().forEach(track => track.stop());
                    adminDesktopShareLocalStream = null;
                }
                
                // 关闭桌面共享WebRTC连接
                if (adminDesktopSharePeerConnection) {
                    adminDesktopSharePeerConnection.close();
                    adminDesktopSharePeerConnection = null;
                }
                
                // 清空桌面共享ICE候选队列
                adminDesktopShareIceCandidateQueue = [];
                
                // 重置状态
                adminDesktopShareState = 'idle';
                activeDesktopShareSession = null;
                currentDesktopShareSessionId = null;
                
                // 如果是当前活跃的桌面共享
                if (data.session_id === activeDesktopShareSession) {
                    activeDesktopShareSession = null;
                    console.log('当前活跃桌面共享已结束');
                }
                
                // 从待接听列表中移除
                incomingDesktopShareSessions.delete(data.session_id);
                
                // 强制更新按钮状态为idle
                updateAdminDesktopShareButton('idle');
                console.log('桌面共享按钮状态已强制更新为idle');
                
                // 处理下一个待接听的桌面共享（如果有的话）
                if (incomingDesktopShareSessions.size > 0) {
                    processNextIncomingDesktopShare();
                }
                
                // 更新会话状态显示
                updateSessionCallStatus();
                
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    const message = data.from === 'user' ? '用户结束桌面共享' : '桌面共享已结束';
                    layer.msg(message, {icon: 1, time: 2000});
                }
            });
            
            // 桌面共享未接通知
            adminSocket.on('desktop_share_missed', function(data) {
                console.log('桌面共享未接通知:', data);
                
                // 防止重复处理
                if (adminDesktopShareState === 'idle') {
                    console.log('桌面共享状态已为空闲，跳过未接处理');
                    return;
                }
                
                // 立即停止桌面共享铃声
                stopAdminDesktopShareRingtone();
                
                // 从待接听列表中移除
                incomingDesktopShareSessions.delete(data.session_id);
                
                // 处理下一个待接听的桌面共享（如果有的话）
                if (incomingDesktopShareSessions.size > 0) {
                    processNextIncomingDesktopShare();
                } else {
                    // 没有排队的桌面共享，直接更新状态
                    updateAdminDesktopShareButton('idle');
                }
                
                // 更新会话状态显示
                updateSessionCallStatus();
                
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg('桌面共享未接听', {icon: 2, time: 2000});
                }
            });
            
            // 用户接听桌面共享
            adminSocket.on('desktop_share_accepted', function(data) {
                console.log('用户接听桌面共享:', data);
                
                // 停止桌面共享铃声
                stopAdminDesktopShareRingtone();
                
                // 更新桌面共享状态
                adminDesktopShareState = 'connected';
                activeDesktopShareSession = data.session_id;
                updateAdminDesktopShareButton('connected');
                
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg('桌面共享已连接', {icon: 1, time: 2000});
                }
            });
            
            // 用户拒绝桌面共享
            adminSocket.on('desktop_share_rejected', function(data) {
                console.log('用户拒绝桌面共享:', data);
                
                // 停止桌面共享铃声
                stopAdminDesktopShareRingtone();
                
                // 重置桌面共享状态
                adminDesktopShareState = 'idle';
                currentDesktopShareSessionId = null;
                updateAdminDesktopShareButton('idle');
                
                // 从待接听列表中移除
                incomingDesktopShareSessions.delete(data.session_id);
                
                // 处理下一个待接听的桌面共享
                processNextIncomingDesktopShare();
                
                // 更新会话状态显示
                updateSessionCallStatus();
                
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg('用户拒绝桌面共享', {icon: 2, time: 2000});
                }
            });
            
            // 桌面共享通知
            adminSocket.on('desktop_share_notification', function(data) {
                console.log('桌面共享通知:', data);
                
                // 在聊天框中添加系统消息
                if (data.session_id === currentSessionId) {
                    addMessageToChat({
                        sender_type: 'system',
                        content: data.content,
                        timestamp: data.timestamp
                    });
                }
                
                if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                    layer.msg(data.content, {icon: 1, time: 3000});
                }
            });
            
            // 处理桌面共享ICE候选
            adminSocket.on('desktop_share_ice_candidate', function(data) {
                console.log('收到桌面共享ICE候选:', data);
                if (adminDesktopSharePeerConnection && data.candidate && data.sender !== 'admin') {
                    // 检查是否已设置远程描述
                    if (adminDesktopSharePeerConnection.remoteDescription) {
                        // 远程描述已设置，直接添加ICE候选
                        adminDesktopSharePeerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                            .then(() => {
                                console.log('管理员桌面共享ICE候选添加成功');
                            })
                            .catch(error => {
                                console.error('管理员桌面共享ICE候选添加失败:', error);
                            });
                    } else {
                        // 远程描述未设置，将ICE候选加入队列
                        console.log('桌面共享远程描述未设置，ICE候选加入队列');
                        adminDesktopShareIceCandidateQueue.push(data.candidate);
                    }
                }
            });
            
            // 处理桌面共享offer
            adminSocket.on('desktop_share_offer_received', function(data) {
                console.log('收到桌面共享offer:', data);
                
                // 检查是否已经在处理中，避免重复处理
                if (adminDesktopShareState !== 'connected') {
                    console.log('桌面共享状态不是connected，忽略offer');
                    return;
                }
                
                if (data.offer) {
                    // 确保WebRTC连接已创建
                    if (!adminDesktopSharePeerConnection) {
                        console.log('WebRTC连接未创建，先创建连接');
                        createAdminDesktopSharePeerConnection().then(() => {
                            handleDesktopShareOffer(data);
                        }).catch(error => {
                            console.error('创建WebRTC连接失败:', error);
                        });
                    } else {
                        console.log('WebRTC连接已存在，直接处理offer');
                        handleDesktopShareOffer(data);
                    }
                }
            });
            
            // 处理桌面共享offer的函数
            function handleDesktopShareOffer(data) {
                if (!adminDesktopSharePeerConnection) {
                    console.error('WebRTC连接不存在，无法处理offer');
                    return;
                }
                
                // 设置远程描述
                adminDesktopSharePeerConnection.setRemoteDescription(new RTCSessionDescription(data.offer))
                    .then(async () => {
                        console.log('桌面共享远程描述设置成功');
                        
                        // 处理队列中的ICE候选
                        while (adminDesktopShareIceCandidateQueue.length > 0) {
                            const candidate = adminDesktopShareIceCandidateQueue.shift();
                            try {
                                await adminDesktopSharePeerConnection.addIceCandidate(new RTCIceCandidate(candidate));
                                console.log('队列中的桌面共享ICE候选添加成功');
                            } catch (error) {
                                console.error('队列中的桌面共享ICE候选添加失败:', error);
                            }
                        }
                        
                        // 创建answer
                        const answer = await adminDesktopSharePeerConnection.createAnswer();
                        await adminDesktopSharePeerConnection.setLocalDescription(answer);
                        
                        // 发送answer给用户
                        adminSocket.emit('admin_desktop_share_answer', {
                            session_id: data.session_id,
                            answer: answer
                        });
                        
                        console.log('桌面共享answer已发送给用户');
                    })
                    .catch(error => {
                        console.error('设置桌面共享远程描述失败:', error);
                    });
            }
            
        } catch (error) {
            console.error('初始化管理员Socket失败:', error);
            updateConnectionStatus('error');
            if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
                layer.msg('初始化聊天失败', {icon: 2});
            }
        }
    }
    
    // 获取活跃会话
    function getActiveSessions() {
        if (adminSocket && adminSocket.connected) {
            console.log('发送获取活跃会话请求...');
            adminSocket.emit('get_active_sessions');
        } else {
            console.log('无法获取活跃会话: Socket未连接');
        }
    }
    
    // 渲染会话列表
    function renderSessionsList() {
        const sessionListEl = document.getElementById('sessionList');
        const noSessionsEl = document.getElementById('noSessions');
        const countEl = document.getElementById('activeSessionCount');
        
        if (!sessionListEl || !countEl) return;
        
        // 更新会话数量
        countEl.textContent = activeSessions.length;
        
        if (activeSessions.length === 0) {
            if (noSessionsEl) noSessionsEl.style.display = 'block';
            sessionListEl.innerHTML = '<div id="noSessions" style="text-align: center; padding: 40px; color: #999;">暂无活跃会话</div>';
            return;
        }
        
        if (noSessionsEl) noSessionsEl.style.display = 'none';
        
        let html = '';
        activeSessions.forEach(function(session) {
            const isSelected = session.session_id === currentSessionId;
            const hasNewMessages = sessionsWithNewMessages.has(session.session_id);
            
            html += `
                <div class="session-item ${isSelected ? 'selected' : ''}" 
                     onclick="selectSession('${session.session_id}')"
                     style="
                        padding: 15px;
                        border-bottom: 1px solid #f0f0f0;
                        cursor: pointer;
                        transition: all 0.2s ease;
                        position: relative;
                        ${isSelected ? 'background: #e3f2fd; border-left: 3px solid #2196f3;' : 'background: white;'}
                     "
                     onmouseover="this.style.background='${isSelected ? '#e3f2fd' : '#f8f9fa'}'"
                     onmouseout="this.style.background='${isSelected ? '#e3f2fd' : 'white'}'">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                        <div style="font-weight: bold; color: #333; font-size: 14px;">
                            <i class="layui-icon layui-icon-user" style="margin-right: 5px; color: #666;"></i>
                            ${session.user_name || '匿名用户'}
                        </div>
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <!-- 语音回拨按钮 -->
                            <button onclick="event.stopPropagation(); voiceCallBack('${session.session_id}')" 
                                    style="
                                        background: #28a745; 
                                        color: white; 
                                        border: none; 
                                        padding: 2px 6px; 
                                        border-radius: 6px; 
                                        font-size: 9px; 
                                        cursor: pointer;
                                        display: flex;
                                        align-items: center;
                                        gap: 2px;
                                    " 
                                    title="语音回拨"
                                    onmouseover="this.style.background='#218838'" 
                                    onmouseout="this.style.background='#28a745'">
                                <i class="layui-icon layui-icon-phone" style="font-size: 9px;"></i>
                                语音
                            </button>
                            <!-- 视频回拨按钮 -->
                            <button onclick="event.stopPropagation(); videoCallBack('${session.session_id}')" 
                                    style="
                                        background: #007bff; 
                                        color: white; 
                                        border: none; 
                                        padding: 2px 6px; 
                                        border-radius: 6px; 
                                        font-size: 9px; 
                                        cursor: pointer;
                                        display: flex;
                                        align-items: center;
                                        gap: 2px;
                                    " 
                                    title="视频回拨"
                                    onmouseover="this.style.background='#0056b3'" 
                                    onmouseout="this.style.background='#007bff'">
                                <i class="layui-icon layui-icon-video" style="font-size: 9px;"></i>
                                视频
                            </button>
                            <!-- 桌面共享按钮 -->
                            <button onclick="event.stopPropagation(); desktopShareCallBack('${session.session_id}')" 
                                    style="
                                        background: #ffc107; 
                                        color: #212529; 
                                        border: none; 
                                        padding: 2px 6px; 
                                        border-radius: 6px; 
                                        font-size: 9px; 
                                        cursor: pointer;
                                        display: flex;
                                        align-items: center;
                                        gap: 2px;
                                    " 
                                    title="桌面共享"
                                    onmouseover="this.style.background='#e0a800'" 
                                    onmouseout="this.style.background='#ffc107'">
                                <i class="layui-icon layui-icon-screen" style="font-size: 9px;"></i>
                                共享
                            </button>
                            <!-- 在线状态 -->
                            <button  style="
                                        background: #ffc107;
                                        color: #212529;
                                        border: none;
                                        padding: 2px 6px;
                                        border-radius: 6px;
                                        font-size: 9px;
                                        cursor: pointer;
                                        display: flex;
                                        align-items: center;
                                        gap: 2px;
                                    " >在线</button>
                        </div>
                    </div>
                    <div style="font-size: 12px; color: #666; margin-bottom: 5px;">
                        <i class="layui-icon layui-icon-cellphone" style="margin-right: 3px;"></i>
                        电话: ${session.user_phone || '未提供'}
                    </div>
                    <div style="font-size: 11px; color: #999; display: flex; justify-content: space-between;">
                        <span>
                            <i class="layui-icon layui-icon-dialogue" style="margin-right: 3px;"></i>
                            消息: ${session.message_count}
                        </span>
                        <span>
                            <i class="layui-icon layui-icon-time" style="margin-right: 3px;"></i>
                            ${session.start_time}
                        </span>
                    </div>
                    ${hasNewMessages ? '<div style="position: absolute; top: 8px; right: 8px; width: 8px; height: 8px; background: #ff5722; border-radius: 50%; border: 2px solid white; box-shadow: 0 0 4px rgba(255,87,34,0.6); animation: pulse 1.5s infinite;"></div>' : ''}
                </div>
            `;
        });
        
        sessionListEl.innerHTML = html;
        
        // 更新通话状态显示
        updateSessionCallStatus();
    }
    
    // 选择会话
    window.selectSession = function(sessionId) {
        if (currentSessionId === sessionId) return;
        
        currentSessionId = sessionId;
        
        // 清除新消息提醒
        clearNewMessageNotification(sessionId);
        
        // 重新渲染会话列表以更新选中状态
        renderSessionsList();
        
        // 渲染聊天界面
        renderChatInterface(sessionId);
        
        // 加载聊天记录
        loadChatHistory(sessionId);
        
        // 监控会话
        if (adminSocket && adminSocket.connected) {
            adminSocket.emit('monitor_session', {session_id: sessionId});
        }
    };
    
    // 渲染聊天界面
    function renderChatInterface(sessionId) {
        const session = activeSessions.find(s => s.session_id === sessionId);
        if (!session) return;
        
        const chatTitleEl = document.getElementById('chatTitle');
        const chatInputAreaEl = document.getElementById('chatInputArea');
        const closeSessionBtnEl = document.getElementById('closeSessionBtn');
        
        if (chatTitleEl) {
            chatTitleEl.innerHTML = `<i class="layui-icon layui-icon-chat"></i> 与 ${session.user_name || '匿名用户'} 的对话`;
        }
        
        if (chatInputAreaEl) {
            chatInputAreaEl.style.display = 'block';
        }
        
        if (closeSessionBtnEl) {
            closeSessionBtnEl.style.display = 'inline-block';
        }
        
        // 清空聊天记录
        const chatMessagesEl = document.getElementById('chatMessages');
        if (chatMessagesEl) {
            chatMessagesEl.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 正在加载聊天记录...</div>';
        }
    }
    
    // 加载聊天记录
    function loadChatHistory(sessionId) {
        // 通过AJAX加载聊天记录
        $.get(`/admin/cms/chat/io/records/${sessionId}`, function(res) {
            if (res.code === 0) {
                const messagesContainer = document.getElementById('chatMessages');
                if (messagesContainer) {
                    messagesContainer.innerHTML = '';
                    
                    res.data.forEach(function(record) {
                        // 对于图片消息，content字段存储的是base64数据
                        if (record.message_type === 'image') {
                            addMessageToChat('[图片]', record.sender_type, record.create_time, record.message_type, record.content);
                        } else {
                            addMessageToChat(record.content, record.sender_type, record.create_time, record.message_type, null);
                        }
                    });
                    
                    if (res.data.length === 0) {
                        messagesContainer.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无聊天记录</div>';
                    }
                }
            } else {
                layer.msg('加载聊天记录失败: ' + res.msg, {icon: 2});
            }
        }).fail(function() {
            layer.msg('加载聊天记录失败', {icon: 2});
        });
    }
    
    // 添加消息到聊天区域
    function addMessageToChat(content, senderType, time, messageType, imageData) {
        const messagesContainer = document.getElementById('chatMessages');
        if (!messagesContainer) return;
        
        // 如果是首次添加消息，清空提示文本
        if (messagesContainer.innerHTML.includes('请选择左侧会话') || 
            messagesContainer.innerHTML.includes('正在加载') ||
            messagesContainer.innerHTML.includes('暂无聊天记录')) {
            messagesContainer.innerHTML = '';
        }
        
        const messageDiv = document.createElement('div');
        
        // 系统消息特殊处理
        if (senderType === 'system') {
            // 检查是否是可回拨的系统消息
            const isCallbackMessage = content.includes('呼叫超时未接听') || 
                                     content.includes('用户取消了通话') ||
                                     content.includes('用户发起语音通话请求');
            
            messageDiv.style.cssText = `
                text-align: center;
                margin: 10px 0;
                padding: 8px 12px;
                background: rgba(108, 117, 125, 0.1);
                border-radius: 15px;
                color: #6c757d;
                font-size: 12px;
                border: 1px solid rgba(108, 117, 125, 0.2);
                max-width: 80%;
                margin-left: auto;
                margin-right: auto;
                ${isCallbackMessage ? 'cursor: pointer; transition: all 0.2s ease;' : ''}
            `;
            
            // 如果是可回拨的消息，添加点击事件和回拨提示
            if (isCallbackMessage) {
                messageDiv.title = '点击回拨用户';
                
                // 添加悬停效果
                messageDiv.onmouseover = function() {
                    this.style.background = 'rgba(0, 123, 255, 0.15)';
                    this.style.borderColor = 'rgba(0, 123, 255, 0.3)';
                    this.style.color = '#0056b3';
                };
                
                messageDiv.onmouseout = function() {
                    this.style.background = 'rgba(108, 117, 125, 0.1)';
                    this.style.borderColor = 'rgba(108, 117, 125, 0.2)';
                    this.style.color = '#6c757d';
                };
                
                // 添加点击事件
                messageDiv.onclick = function() {
                    if (currentSessionId) {
                        console.log('点击系统消息回拨用户:', currentSessionId);
                        callbackUser(currentSessionId);
                    }
                };
            }
            
            messageDiv.innerHTML = `
                <div style="margin-bottom: 3px;">
                    ${isCallbackMessage ? '📞' : '💬'} ${content}
                    ${isCallbackMessage ? '<span style="margin-left: 8px; font-size: 10px; opacity: 0.7;">(点击回拨)</span>' : ''}
                </div>
                <div style="font-size: 10px; opacity: 0.7;">${time || new Date().toLocaleTimeString()}</div>
            `;
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            return;
        }
        
        // 普通用户和管理员消息处理
        const isAdmin = senderType === 'admin';
        
        messageDiv.style.cssText = `
            margin-bottom: 15px;
            display: flex;
            ${isAdmin ? 'justify-content: flex-end;' : 'justify-content: flex-start;'}
        `;
        
        let messageContent;
        if (messageType === 'image' && imageData) {
            // 为图片生成唯一ID
            const imageId = 'img_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            messageContent = `<img id="${imageId}" src="${imageData}" style="
                max-width: 100%;
                max-height: 200px;
                border-radius: 8px;
                cursor: pointer;
                transition: transform 0.2s;
            " onmouseover="this.style.transform='scale(1.05)'" 
               onmouseout="this.style.transform='scale(1)'">`;
            
            // 延迟绑定点击事件，避免引号问题
            setTimeout(function() {
                const imgElement = document.getElementById(imageId);
                if (imgElement) {
                    imgElement.onclick = function() {
                        showImageModal(imageData);
                    };
                }
            }, 100);
        } else {
            messageContent = `<div style="line-height: 1.4; margin-bottom: 6px;">${content}</div>`;
        }
        
        messageDiv.innerHTML = `
            <div style="
                max-width: 70%;
                padding: ${messageType === 'image' ? '8px' : '12px 16px'};
                border-radius: 18px;
                background: ${isAdmin ? '#2196f3' : '#f1f3f4'};
                color: ${isAdmin ? 'white' : '#333'};
                word-wrap: break-word;
                position: relative;
                box-shadow: 0 1px 2px rgba(0,0,0,0.1);
                ${isAdmin ? 'border-bottom-right-radius: 4px;' : 'border-bottom-left-radius: 4px;'}
            ">
                <div style="
                    display: flex;
                    align-items: center;
                    margin-bottom: 6px;
                    font-size: 12px;
                    opacity: 0.8;
                ">
                    <i class="layui-icon ${isAdmin ? 'layui-icon-service' : 'layui-icon-user'}" style="margin-right: 4px;"></i>
                    <strong>${isAdmin ? '客服' : '用户'}</strong>
                </div>
                ${messageContent}
                <div style="
                    font-size: 10px;
                    opacity: 0.6;
                    text-align: right;
                ">${time || new Date().toLocaleTimeString()}</div>
            </div>
        `;
        
        messagesContainer.appendChild(messageDiv);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
    
    // 显示图片模态框
    function showImageModal(imageData) {
        // 创建模态框
        const modal = document.createElement('div');
        modal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
            cursor: pointer;
        `;
        
        const img = document.createElement('img');
        img.src = imageData;
        img.style.cssText = `
            max-width: 90%;
            max-height: 90%;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        `;
        
        modal.appendChild(img);
        document.body.appendChild(modal);
        
        // 点击模态框关闭
        modal.onclick = function() {
            document.body.removeChild(modal);
        };
        
        // ESC键关闭
        const escHandler = function(event) {
            if (event.key === 'Escape') {
                document.body.removeChild(modal);
                document.removeEventListener('keydown', escHandler);
            }
        };
        document.addEventListener('keydown', escHandler);
    }
    
    // 播放提示音
    function playMessageSound() {
        // 只有在用户已经与页面交互过才播放提示音
        if (!userHasInteracted) {
            console.log('用户尚未交互，跳过提示音播放');
            return;
        }
        
        try {
            // 创建AudioContext
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            
            // 如果AudioContext被暂停，恢复它
            if (audioContext.state === 'suspended') {
                audioContext.resume();
            }
            
            // 创建振荡器和增益节点
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            // 设置音频参数
            oscillator.type = 'sine';
            oscillator.frequency.setValueAtTime(800, audioContext.currentTime); // 800Hz，更悦耳的音调
            oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.1); // 0.1秒后降到600Hz
            
            // 设置音量渐变
            gainNode.gain.setValueAtTime(0, audioContext.currentTime);
            gainNode.gain.linearRampToValueAtTime(0.2, audioContext.currentTime + 0.01);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
            
            // 连接节点
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            // 播放音频
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.3);
            
            console.log('提示音已播放');
            
            // 清理资源
            oscillator.onended = function() {
                audioContext.close().catch(e => console.log('AudioContext已关闭'));
            };
            
        } catch (error) {
            console.error('播放提示音失败:', error);
        }
    }
    
    // 处理图片粘贴
    function handleImagePaste(event) {
        console.log('粘贴事件触发:', event);
        
        // jQuery事件对象处理 - 优先尝试originalEvent
        let clipboardData = null;
        
        if (event.originalEvent && event.originalEvent.clipboardData) {
            clipboardData = event.originalEvent.clipboardData;
            console.log('使用originalEvent.clipboardData');
        } else if (event.clipboardData) {
            clipboardData = event.clipboardData;
            console.log('使用event.clipboardData');
        } else {
            console.log('没有找到clipboardData，忽略粘贴事件');
            return;
        }
        
        if (!clipboardData || !clipboardData.items) {
            console.log('clipboardData.items不存在，忽略粘贴事件');
            return;
        }
        
        const items = clipboardData.items;
        console.log('剪贴板项目数量:', items.length);
        
        let hasImage = false;
        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            console.log('项目类型:', item.type);
            
            if (item.type.indexOf('image') !== -1) {
                hasImage = true;
                console.log('检测到图片，阻止默认行为');
                event.preventDefault();
                
                const file = item.getAsFile();
                if (!file) {
                    console.log('无法获取文件对象');
                    continue;
                }
                
                console.log('开始读取图片文件，文件大小:', file.size);
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    const imageData = e.target.result;
                    console.log('图片读取成功，数据长度:', imageData.length);
                    sendImageMessage(imageData);
                };
                
                reader.onerror = function(e) {
                    console.error('图片读取失败:', e);
                    layer.msg('图片读取失败', {icon: 2});
                };
                
                reader.readAsDataURL(file);
                break;
            }
        }
        
        // 如果剪贴板中没有图片，给出提示
        if (!hasImage && items.length > 0) {
            console.log('剪贴板中没有检测到图片内容');
            // 不显示提示消息，让文本正常粘贴
        }
    }
    
    // 发送图片消息
    function sendImageMessage(imageData) {
        if (!currentSessionId) {
            layer.msg('请先选择一个会话', {icon: 2});
            return;
        }
        
        if (!adminSocket || !adminSocket.connected) {
            layer.msg('连接已断开，请刷新页面', {icon: 2});
            return;
        }
        
        // 发送图片消息
        adminSocket.emit('send_admin_message', {
            session_id: currentSessionId,
            content: '[图片]',
            message_type: 'image',
            image_data: imageData
        });
        
        console.log('管理员发送图片消息');
    }
    
    // 发送消息
    function sendMessage() {
        const input = document.getElementById('messageInput');
        if (!input) return;
        
        const content = input.value.trim();
        if (!content) {
            layer.msg('请输入消息内容', {icon: 2});
            return;
        }
        
        if (!currentSessionId) {
            layer.msg('请先选择一个会话', {icon: 2});
            return;
        }
        
        if (!adminSocket || !adminSocket.connected) {
            layer.msg('连接已断开，请刷新页面', {icon: 2});
            return;
        }
        
        // 发送文本消息
        adminSocket.emit('send_admin_message', {
            session_id: currentSessionId,
            content: content,
            message_type: 'text'
        });
    }
    
    // 关闭会话
    function closeSession() {
        if (!currentSessionId) {
            layer.msg('请先选择一个会话', {icon: 2});
            return;
        }
        
        layer.confirm('确定要关闭此会话吗？', {
            btn: ['确定', '取消']
        }, function(index) {
            if (adminSocket && adminSocket.connected) {
                adminSocket.emit('close_session', {
                    session_id: currentSessionId
                });
            }
            layer.close(index);
        });
    }
    
    // 事件绑定
    function bindEvents() {
        // 添加用户交互检测
        const userInteractionEvents = ['click', 'touchstart', 'keydown', 'mousedown'];
        userInteractionEvents.forEach(eventType => {
            document.addEventListener(eventType, function() {
                if (!userHasInteracted) {
                    userHasInteracted = true;
                    console.log('用户已与页面交互，启用提示音功能');
                    // 初始化管理员音频系统
                    initAdminAudio();
                }
            }, { once: true }); // once: true 确保只触发一次
        });
        
        // 发送按钮点击
        $('#sendBtn').on('click', sendMessage);
        
        // 输入框回车发送 (textarea支持)
        $('#messageInput').on('keypress', function(e) {
            if (e.which === 13) { // Enter键
                if (e.shiftKey) {
                    // Shift+Enter: 换行，不发送消息
                    return true;
                } else {
                    // 单独Enter: 发送消息
                    e.preventDefault();
                    sendMessage();
                    return false;
                }
            }
        });

        // 输入框粘贴图片
        $('#messageInput').on('paste', handleImagePaste);
        
        // 管理员图片输入框处理
        $('#adminImageInput').on('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                // 检查文件类型
                if (!file.type.startsWith('image/')) {
                    layer.msg('请选择图片文件', {icon: 2});
                    event.target.value = '';
                    return;
                }
                
                // 检查文件大小 (限制为5MB)
                const maxSize = 5 * 1024 * 1024; // 5MB
                if (file.size > maxSize) {
                    layer.msg('图片文件过大，请选择小于5MB的图片', {icon: 2});
                    event.target.value = '';
                    return;
                }
                
                console.log('管理员开始读取选择的图片文件:', file.name, '大小:', file.size);
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const imageData = e.target.result;
                    console.log('管理员图片读取成功，发送图片消息');
                    sendImageMessage(imageData);
                    
                    // 清空输入框，允许重复选择同一文件
                    event.target.value = '';
                };
                
                reader.onerror = function(e) {
                    console.error('管理员图片读取失败:', e);
                    layer.msg('图片读取失败，请重试', {icon: 2});
                    event.target.value = '';
                };
                
                reader.readAsDataURL(file);
            }
        });
        
        // 点击外部关闭管理员表情面板
        $(document).on('click', function(e) {
            const emojiPanel = document.getElementById('adminEmojiPanel');
            const emojiBtn = document.querySelector('button[onclick="toggleAdminEmoji()"]');
            
            if (emojiPanel && emojiPanel.style.display === 'block') {
                if (!emojiPanel.contains(e.target) && !emojiBtn.contains(e.target)) {
                    emojiPanel.style.display = 'none';
                }
            }
        });
        
        // 刷新按钮
        $('#refreshBtn').on('click', function() {
            getActiveSessions();
        });
        
        // 关闭会话按钮
        $('#closeSessionBtn').on('click', closeSession);
        
        // 初始化Socket连接
        initAdminSocket();
        
        // 定时刷新会话列表
        var refreshTimer = setInterval(function() {
            if (adminSocket && adminSocket.connected && !document.hidden) {
                getActiveSessions();
            }
        }, 30000); // 30秒刷新一次
        
        // 只在页面真正关闭时断开连接（不包括切换标签、最小化等）
        window.addEventListener('beforeunload', function(event) {
            // 只在真正关闭标签页时断开连接
            if (adminSocket && adminSocket.connected) {
                console.log('管理员页面关闭，断开WebSocket连接');
                adminSocket.disconnect();
            }
        });
        
        // 页面可见性优化：页面隐藏时暂停定时操作，保持连接
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                console.log('管理员页面隐藏，暂停定时刷新但保持WebSocket连接');
                // 页面隐藏时暂停定时刷新等操作，但保持连接
            } else {
                console.log('管理员页面重新可见，恢复定时刷新');
                // 页面重新可见时立即刷新一次
                if (adminSocket && adminSocket.connected) {
                    getActiveSessions();
                }
            }
        });
    }
    
    // 绑定事件
    bindEvents();
}

// 更新会话通话状态显示
function updateSessionCallStatus() {
    // 更新会话列表中的通话状态显示
    const sessionItems = document.querySelectorAll('[onclick*="selectSession"]');
    
    sessionItems.forEach(item => {
        const onclickAttr = item.getAttribute('onclick');
        const sessionIdMatch = onclickAttr.match(/selectSession\('([^']+)'\)/);
        
        if (sessionIdMatch) {
            const sessionId = sessionIdMatch[1];
            
            // 移除之前的通话状态指示器
            const existingCallStatus = item.querySelector('.call-status-indicator');
            if (existingCallStatus) {
                existingCallStatus.remove();
            }
            
            // 添加新的通话状态指示器
            let statusHtml = '';
            let statusClass = '';
            
            if (activeCallSession === sessionId) {
                statusHtml = '🔊 语音通话中';
                statusClass = 'call-active';
            } else if (incomingCallSessions.has(sessionId)) {
                statusHtml = '📞 语音来电';
                statusClass = 'call-incoming';
            } else if (activeVideoCallSession === sessionId) {
                statusHtml = '📹 视频通话中';
                statusClass = 'video-call-active';
            } else if (incomingVideoCallSessions.has(sessionId)) {
                statusHtml = '📹 视频来电';
                statusClass = 'video-call-incoming';
            } else if (activeDesktopShareSession === sessionId) {
                statusHtml = '🖥️ 桌面共享中';
                statusClass = 'desktop-share-active';
            } else if (incomingDesktopShareSessions.has(sessionId)) {
                statusHtml = '🖥️ 桌面共享来电';
                statusClass = 'desktop-share-incoming';
            }
            
            if (statusHtml) {
                const statusElement = document.createElement('div');
                statusElement.className = `call-status-indicator ${statusClass}`;
                statusElement.style.cssText = `
                    position: absolute;
                    top: 5px;
                    left: 5px;
                    background: ${statusClass.includes('desktop-share') ? '#4caf50' : (statusClass.includes('video') ? '#9c27b0' : (statusClass === 'call-active' ? '#28a745' : '#ff5722'))};
                    color: white;
                    padding: 2px 6px;
                    border-radius: 8px;
                    font-size: 10px;
                    font-weight: bold;
                    z-index: 10;
                `;
                statusElement.textContent = statusHtml;
                item.style.position = 'relative';
                item.appendChild(statusElement);
            }
        }
    });
    
    console.log('会话通话状态已更新 - 活跃语音:', activeCallSession, '待接听语音:', Array.from(incomingCallSessions), '活跃视频:', activeVideoCallSession, '待接听视频:', Array.from(incomingVideoCallSessions), '活跃桌面共享:', activeDesktopShareSession, '待接听桌面共享:', Array.from(incomingDesktopShareSessions));
}

// 回拨用户
function callbackUser(sessionId) {
    console.log('管理员回拨用户，会话ID:', sessionId);
    
    if (!adminSocket || !adminSocket.connected) {
        console.log('管理员端未连接，无法回拨');
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('连接已断开，无法回拨', {icon: 2});
        }
        return;
    }
    
    try {
        // 设置管理员为回拨状态
        adminCallState = 'calling';
        currentCallSessionId = sessionId;
        updateAdminCallButton('calling');
        
        // 播放回拨铃声
        playAdminRingtone();
        console.log('开始播放管理员回拨铃声');
        
        // 发送回拨请求
        adminSocket.emit('admin_voice_call_callback', {
            session_id: sessionId,
            type: 'callback_request'
        });
        
        console.log('管理员回拨请求已发送:', sessionId);
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('正在回拨用户，请等待用户接听...', {icon: 1, time: 3000});
        }
        
    } catch (error) {
        console.error('回拨用户失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('回拨失败', {icon: 2});
        }
    }
}

// 处理用户接听
async function handleUserAccepted(sessionId) {
    console.log('处理用户接听，会话ID:', sessionId);
    
    try {
        // 设置当前会话ID
        currentCallSessionId = sessionId;
        
        // 创建WebRTC连接
        await createAdminPeerConnection();
        
        // 创建offer
        const offer = await adminPeerConnection.createOffer();
        await adminPeerConnection.setLocalDescription(offer);
        
        console.log('管理员创建offer成功，发送给用户');
        
        // 发送offer给用户
        adminSocket.emit('admin_voice_call_answer', {
            session_id: sessionId,
            offer: offer
        });
        
        // 更新按钮状态
        adminCallState = 'connected';
        updateAdminCallButton('connected');
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('用户已接听，正在建立音频连接...', {icon: 1});
        }
        
        console.log('WebRTC offer已发送给用户');
        
    } catch (error) {
        console.error('处理用户接听失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('建立音频连接失败: ' + error.message, {icon: 2});
        }
        resetAdminCallState();
    }
}

// 处理用户接听视频通话
async function handleUserVideoAccepted(sessionId) {
    console.log('处理用户接听视频通话，会话ID:', sessionId);
    
    try {
        // 设置当前会话ID
        currentVideoCallSessionId = sessionId;
        
        // 初始化视频元素
        initAdminVideoElements();
        
        // 获取摄像头权限并显示本地视频
        const stream = await getAdminVideo();
        if (adminVideoLocalVideo && stream) {
            adminVideoLocalVideo.srcObject = stream;
            console.log('管理员本地视频流已设置');
            
            // 确保本地视频开始播放
            adminVideoLocalVideo.play().then(() => {
                console.log('管理员本地视频开始播放');
            }).catch(error => {
                console.error('管理员本地视频播放失败:', error);
            });
        } else {
            console.error('管理员本地视频元素或流不存在');
        }
        
        // 创建视频WebRTC连接
        await createAdminVideoPeerConnection();
        
        // 创建offer
        const offer = await adminVideoPeerConnection.createOffer();
        await adminVideoPeerConnection.setLocalDescription(offer);
        
        console.log('管理员创建视频offer成功，发送给用户');
        
        // 发送offer给用户
        adminSocket.emit('admin_video_call_answer', {
            session_id: sessionId,
            offer: offer
        });
        
        // 更新按钮状态
        adminVideoCallState = 'connected';
        updateAdminVideoCallButton('connected');
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('用户已接听视频通话，正在建立视频连接...', {icon: 1});
        }
        
        console.log('视频WebRTC offer已发送给用户');
        
    } catch (error) {
        console.error('处理用户接听视频通话失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('建立视频连接失败: ' + error.message, {icon: 2});
        }
        resetAdminVideoCallState();
    }
}

// 接听视频通话
async function answerVideoCall() {
    if (!adminSocket || !adminSocket.connected || !currentVideoCallSessionId) {
        if (typeof layer !== 'undefined') {
            layer.msg('无法接听视频通话', {icon: 2});
        } else {
            alert('无法接听视频通话');
        }
        return;
    }
    
    try {
        // 停止视频铃声
        stopAdminVideoRingtone();
        
        // 设置活跃视频通话会话
        activeVideoCallSession = currentVideoCallSessionId;
        
        // 从待接听列表中移除当前会话
        incomingVideoCallSessions.delete(currentVideoCallSessionId);
        
        // 更新剩余队列用户的位置
        updateVideoQueuePositions();
        
        console.log('管理员接听视频通话，活跃会话:', activeVideoCallSession, '剩余队列:', Array.from(incomingVideoCallSessions));
        
        // 初始化视频元素
        initAdminVideoElements();
        
        // 获取摄像头权限并显示本地视频
        const stream = await getAdminVideo();
        if (adminVideoLocalVideo && stream) {
            adminVideoLocalVideo.srcObject = stream;
            console.log('管理员本地视频流已设置');
            
            // 确保本地视频开始播放
            adminVideoLocalVideo.play().then(() => {
                console.log('管理员本地视频开始播放');
            }).catch(error => {
                console.error('管理员本地视频播放失败:', error);
            });
        } else {
            console.error('管理员本地视频元素或流不存在');
        }
        
        // 创建视频WebRTC连接
        await createAdminVideoPeerConnection();
        
        // 创建应答
        const offer = await adminVideoPeerConnection.createOffer();
        await adminVideoPeerConnection.setLocalDescription(offer);
        
        console.log('管理员创建视频应答，发送offer');
        
        // 发送接听信号和offer
        adminSocket.emit('admin_video_call_answer', {
            session_id: currentVideoCallSessionId,
            offer: offer
        });
        
        updateAdminVideoCallButton('connected');
        if (typeof layer !== 'undefined') {
            layer.msg('视频通话已连接，正在建立视频连接...', {icon: 1});
        }
        
        // 发送接听通知到聊天框
        adminSocket.emit('video_call_notification', {
            session_id: currentVideoCallSessionId,
            type: 'answer',
            content: `📹 管理员接听视频通话 - ${new Date().toLocaleTimeString()}`,
            timestamp: new Date().toLocaleString()
        });
        
        // 更新会话列表显示
        updateSessionCallStatus();
        
    } catch (error) {
        console.error('接听视频通话失败:', error);
        if (typeof layer !== 'undefined') {
            layer.msg('接听视频通话失败: ' + error.message, {icon: 2});
        }
        resetAdminVideoCallState();
    }
}

// 结束视频通话
function endVideoCall() {
    if (!adminSocket || !adminSocket.connected || !currentVideoCallSessionId) {
        return;
    }
    
    // 停止视频铃声
    stopAdminVideoRingtone();
    
    // 清理视频WebRTC资源
    cleanupAdminVideoCall();
    
    // 发送结束视频通话信号
    adminSocket.emit('admin_video_call_end', {
        session_id: currentVideoCallSessionId
    });
    
    // 发送结束视频通话通知到聊天框
    adminSocket.emit('video_call_notification', {
        session_id: currentVideoCallSessionId,
        type: 'end',
        content: `📹 管理员结束视频通话 - ${new Date().toLocaleTimeString()}`,
        timestamp: new Date().toLocaleString()
    });
    
    resetAdminVideoCallState();
    if (typeof layer !== 'undefined') {
        layer.msg('视频通话已结束', {icon: 1});
    }
}

// 获取管理员视频设备
async function getAdminVideo() {
    try {
        if (adminVideoLocalStream) {
            console.log('管理员视频流已存在，无需重复获取');
            return adminVideoLocalStream;
        }
        
        console.log('请求管理员摄像头权限...');
        adminVideoLocalStream = await navigator.mediaDevices.getUserMedia({
            audio: {
                echoCancellation: true,
                noiseSuppression: true,
                autoGainControl: true
            },
            video: {
                width: { ideal: 1280 },
                height: { ideal: 720 },
                frameRate: { ideal: 30 }
            }
        });
        console.log('管理员摄像头获取成功，轨道数量:', adminVideoLocalStream.getTracks().length);
        adminVideoLocalStream.getTracks().forEach(track => {
            console.log('管理员视频轨道:', track.kind, '状态:', track.readyState);
        });
        return adminVideoLocalStream;
    } catch (error) {
        console.error('获取管理员摄像头失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('无法访问摄像头，请检查权限设置', {icon: 2});
        }
        throw error;
    }
}

// 创建管理员视频WebRTC连接
async function createAdminVideoPeerConnection() {
    try {
        console.log('创建管理员视频WebRTC连接...');
        adminVideoPeerConnection = new RTCPeerConnection(adminRtcConfig);
        
        // 添加本地音视频流
        const stream = await getAdminVideo();
        stream.getTracks().forEach(track => {
            adminVideoPeerConnection.addTrack(track, stream);
            console.log('管理员音视频轨道已添加到连接:', track.kind);
        });
        
        // 处理远程音视频流
        adminVideoPeerConnection.ontrack = function(event) {
            console.log('收到远程音视频流，轨道数量:', event.streams.length);
            if (event.streams && event.streams.length > 0) {
                console.log('远程流信息:', event.streams[0].getTracks().map(track => track.kind));
                if (adminVideoRemoteVideo) {
                    adminVideoRemoteVideo.srcObject = event.streams[0];
                    console.log('远程音视频流已设置到播放元素');
                    
                    // 确保视频元素开始播放
                    adminVideoRemoteVideo.play().then(() => {
                        console.log('远程视频开始播放');
                    }).catch(error => {
                        console.error('远程视频播放失败:', error);
                    });
                } else {
                    console.error('管理员远程视频元素不存在');
                }
            } else {
                console.error('远程流为空或未定义');
            }
        };
        
        // 处理ICE候选
        adminVideoPeerConnection.onicecandidate = function(event) {
            if (event.candidate) {
                console.log('发送管理员视频ICE候选');
                adminSocket.emit('video_ice_candidate', {
                    session_id: currentVideoCallSessionId,
                    candidate: event.candidate,
                    sender: 'admin'
                });
            }
        };
        
        // 连接状态变化
        adminVideoPeerConnection.onconnectionstatechange = function() {
            console.log('管理员视频WebRTC连接状态:', adminVideoPeerConnection.connectionState);
            if (adminVideoPeerConnection.connectionState === 'connected') {
                console.log('管理员视频通话已建立');
            } else if (adminVideoPeerConnection.connectionState === 'disconnected' || 
                      adminVideoPeerConnection.connectionState === 'failed') {
                console.log('管理员视频通话连接断开');
                cleanupAdminVideoCall();
            }
        };
        
        return adminVideoPeerConnection;
    } catch (error) {
        console.error('创建管理员视频WebRTC连接失败:', error);
        throw error;
    }
}

// 清理管理员视频通话资源
function cleanupAdminVideoCall() {
    console.log('开始清理管理员视频通话资源...');
    
    // 关闭视频WebRTC连接
    if (adminVideoPeerConnection) {
        adminVideoPeerConnection.close();
        adminVideoPeerConnection = null;
        console.log('管理员视频WebRTC连接已关闭');
    } else {
        console.log('管理员视频WebRTC连接不存在，无需关闭');
    }
    
    // 停止本地视频流
    if (adminVideoLocalStream) {
        adminVideoLocalStream.getTracks().forEach(track => {
            track.stop();
            console.log('管理员视频轨道已停止:', track.kind);
        });
        adminVideoLocalStream = null;
        console.log('管理员本地视频流已清理');
    } else {
        console.log('管理员本地视频流不存在，无需清理');
    }
    
    // 清理远程视频
    if (adminVideoRemoteVideo) {
        adminVideoRemoteVideo.srcObject = null;
        adminVideoRemoteVideo.remove(); // 从DOM中移除
        adminVideoRemoteVideo = null;
        console.log('管理员远程视频已清理');
    } else {
        console.log('管理员远程视频元素不存在，无需清理');
    }
    
    // 清理本地视频
    if (adminVideoLocalVideo) {
        adminVideoLocalVideo.srcObject = null;
        adminVideoLocalVideo.remove(); // 从DOM中移除
        adminVideoLocalVideo = null;
        console.log('管理员本地视频已清理');
    } else {
        console.log('管理员本地视频元素不存在，无需清理');
    }
    
    // 清空视频ICE候选队列
    adminVideoIceCandidateQueue = [];
    console.log('管理员视频ICE候选队列已清空');
    
    console.log('管理员视频通话资源清理完成');
}

// 初始化管理员视频元素
function initAdminVideoElements() {
    console.log('开始初始化管理员视频元素...');
    
    // 创建管理员本地视频元素
    if (!adminVideoLocalVideo) {
        adminVideoLocalVideo = document.createElement('video');
        adminVideoLocalVideo.autoplay = true;
        adminVideoLocalVideo.playsInline = true;
        adminVideoLocalVideo.muted = true; // 本地视频静音避免回声
        adminVideoLocalVideo.style.cssText = `
            position: fixed;
            top: 20px;
            left: 20px;
            width: 200px;
            height: 150px;
            border: 2px solid #9c27b0;
            border-radius: 8px;
            background: #000;
            z-index: 1000;
        `;
        document.body.appendChild(adminVideoLocalVideo);
        console.log('管理员本地视频元素已创建并添加到DOM');
    } else {
        console.log('管理员本地视频元素已存在');
    }
    
    // 创建管理员远程视频元素
    if (!adminVideoRemoteVideo) {
        adminVideoRemoteVideo = document.createElement('video');
        adminVideoRemoteVideo.autoplay = true;
        adminVideoRemoteVideo.playsInline = true;
        adminVideoRemoteVideo.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 80vw;
            height: 60vh;
            border: 2px solid #28a745;
            border-radius: 8px;
            background: #000;
            z-index: 1000;
        `;
        document.body.appendChild(adminVideoRemoteVideo);
        console.log('管理员远程视频元素已创建并添加到DOM');
    } else {
        console.log('管理员远程视频元素已存在');
    }
    
    console.log('管理员视频元素初始化完成');
}

// 更新管理员视频通话按钮状态
function updateAdminVideoCallButton(state) {
    const videoCallBtn = document.getElementById('adminVideoCallBtn');
    const videoCallBtnText = document.getElementById('adminVideoCallBtnText');
    const rejectBtn = document.getElementById('adminRejectCallBtn');
    
    if (!videoCallBtn || !videoCallBtnText || !rejectBtn) return;
    
    adminVideoCallState = state;
    
    switch (state) {
        case 'idle':
            videoCallBtn.style.display = 'none';
            rejectBtn.style.display = 'none';
            break;
        case 'incoming':
            videoCallBtn.style.display = 'inline-block';
            videoCallBtn.style.background = '#9c27b0';
            videoCallBtnText.textContent = '接听视频';
            rejectBtn.style.display = 'inline-block';
            break;
        case 'calling':
            videoCallBtn.style.display = 'inline-block';
            videoCallBtn.style.background = '#ff9800';
            videoCallBtnText.textContent = '回拨视频中...';
            rejectBtn.style.display = 'inline-block';
            rejectBtn.innerHTML = '<i class="layui-icon layui-icon-close"></i> 取消回拨';
            break;
        case 'connected':
            videoCallBtn.style.display = 'inline-block';
            videoCallBtn.style.background = '#f44336';
            videoCallBtnText.textContent = '结束视频';
            rejectBtn.style.display = 'none'; // 通话结束后隐藏拒绝按钮
            break;
    }
}

// 重置管理员视频通话状态
function resetAdminVideoCallState() {
    console.log('开始重置管理员视频通话状态');
    
    adminVideoCallState = 'idle';
    activeVideoCallSession = null;
    currentVideoCallSessionId = null;
    console.log('已重置视频通话状态变量');
    
    stopAdminVideoRingtone(); // 确保视频铃声停止
    console.log('已停止视频铃声');
    
    cleanupAdminVideoCall(); // 清理视频WebRTC资源
    console.log('已清理视频WebRTC资源');
    
    // 如果有排队的视频通话，处理下一个
    if (incomingVideoCallSessions.size > 0) {
        console.log('活跃视频通话结束，处理队列中的下一个视频通话');
        processNextIncomingVideoCall();
    } else {
        // 没有排队的视频通话，完全重置
        console.log('没有排队的视频通话，完全重置状态');
        updateAdminVideoCallButton('idle');
        updateSessionCallStatus();
    }
    
    console.log('管理员视频通话状态重置完成');
}

// 处理下一个待接听的视频通话
function processNextIncomingVideoCall() {
    if (incomingVideoCallSessions.size > 0) {
        // 获取下一个视频通话
        const nextSessionId = incomingVideoCallSessions.values().next().value;
        currentVideoCallSessionId = nextSessionId;
        
        updateAdminVideoCallButton('incoming');
        playAdminVideoRingtone();
        
        console.log('切换到下一个视频通话:', nextSessionId, '还有', incomingVideoCallSessions.size - 1, '个待接听');
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg(`切换到下一个视频通话，还有 ${incomingVideoCallSessions.size - 1} 个待接听`, {
                icon: 1,
                time: 2000
            });
        }
        
        // 更新所有排队用户的位置
        updateVideoQueuePositions();
    } else {
        resetAdminVideoCallState();
    }
    
    updateSessionCallStatus();
}

// 更新视频队列中所有用户的位置
function updateVideoQueuePositions() {
    console.log('更新视频队列位置，当前队列:', Array.from(incomingVideoCallSessions));
    
    let position = 1;
    for (const sessionId of incomingVideoCallSessions) {
        if (sessionId !== currentVideoCallSessionId) {
            // 发送更新的队列位置给用户
            adminSocket.emit('video_call_queue_status', {
                session_id: sessionId,
                status: 'queued',
                position: position,
                message: position === 1 ? 
                    '您是下一位，请保持等待...' : 
                    `当前有 ${position - 1} 人在您前面排队，请稍候...`
            });
            position++;
        }
    }
}

// 桌面共享相关函数

// 处理管理员桌面共享
function handleAdminDesktopShare() {
    console.log('管理员桌面共享按钮被点击，当前状态:', adminDesktopShareState);
    
    switch (adminDesktopShareState) {
        case 'idle':
            console.log('桌面共享状态为空闲，无法处理');
            break;
        case 'incoming':
            console.log('接听桌面共享');
            answerDesktopShare();
            break;
        case 'connected':
            console.log('结束桌面共享');
            endDesktopShare();
            break;
        default:
            console.log('未知的桌面共享状态:', adminDesktopShareState);
    }
}

// 接听桌面共享
async function answerDesktopShare() {
    console.log('管理员接听桌面共享');
    
    try {
        // 立即停止桌面共享铃声
        stopAdminDesktopShareRingtone();
        
        // 更新桌面共享状态为已接听
        adminDesktopShareState = 'connected';
        activeDesktopShareSession = currentDesktopShareSessionId;
        updateAdminDesktopShareButton('connected');
        
        // 不立即创建WebRTC连接，等待收到offer后再创建
        // WebRTC连接将在desktop_share_offer_received中创建
        
        // 发送接听确认
        adminSocket.emit('admin_desktop_share_answer', {
            session_id: currentDesktopShareSessionId
        });
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('已接听桌面共享', {icon: 1, time: 2000});
        }
        
    } catch (error) {
        console.error('接听桌面共享失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('接听桌面共享失败', {icon: 2, time: 2000});
        }
        updateAdminDesktopShareButton('idle');
    }
}

// 结束桌面共享
function endDesktopShare() {
    console.log('管理员结束桌面共享');
    
    // 防止重复发送事件
    if (adminDesktopShareState === 'idle') {
        console.log('桌面共享状态已为空闲，跳过结束事件');
        return;
    }
    
    if (adminSocket && adminSocket.connected) {
        adminSocket.emit('admin_desktop_share_end', {
            session_id: currentDesktopShareSessionId
        });
    }
    
    // 直接清理资源，不调用其他函数
    console.log('开始清理管理员桌面共享资源');
    
    // 停止桌面共享铃声
    stopAdminDesktopShareRingtone();
    
    // 关闭桌面共享弹窗
    closeDesktopSharePopup();
    
    // 清理桌面共享流
    if (adminDesktopShareLocalStream) {
        adminDesktopShareLocalStream.getTracks().forEach(track => track.stop());
        adminDesktopShareLocalStream = null;
        console.log('管理员桌面共享流已清理');
    }
    
    // 关闭桌面共享WebRTC连接
    if (adminDesktopSharePeerConnection) {
        adminDesktopSharePeerConnection.close();
        adminDesktopSharePeerConnection = null;
        console.log('管理员桌面共享WebRTC连接已关闭');
    }
    
    // 清空桌面共享ICE候选队列
    adminDesktopShareIceCandidateQueue = [];
    console.log('管理员桌面共享ICE候选队列已清空');
    
    // 保存当前会话ID，用于清理
    const sessionIdToClean = currentDesktopShareSessionId;
    
    // 重置状态
    adminDesktopShareState = 'idle';
    activeDesktopShareSession = null;
    currentDesktopShareSessionId = null;
    
    // 从待接听列表中移除当前会话
    if (sessionIdToClean) {
        incomingDesktopShareSessions.delete(sessionIdToClean);
        console.log('从待接听列表中移除会话:', sessionIdToClean);
    }
    
    // 更新UI状态
    updateAdminDesktopShareButton('idle');
    updateSessionCallStatus();
    
    console.log('管理员桌面共享资源清理完成');
    
    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
        layer.msg('桌面共享已结束', {icon: 1, time: 2000});
    }
}

// 清理管理员桌面共享资源
function cleanupAdminDesktopShare() {
    console.log('开始清理管理员桌面共享资源');
    
    // 防止重复清理
    if (adminDesktopShareState === 'idle') {
        console.log('桌面共享状态已为空闲，跳过清理');
        return;
    }
    
    // 停止桌面共享铃声
    stopAdminDesktopShareRingtone();
    
    // 关闭桌面共享弹窗
    closeDesktopSharePopup();
    
    // 清理桌面共享流
    if (adminDesktopShareLocalStream) {
        adminDesktopShareLocalStream.getTracks().forEach(track => track.stop());
        adminDesktopShareLocalStream = null;
        console.log('管理员桌面共享流已清理');
    }
    
    // 关闭桌面共享WebRTC连接
    if (adminDesktopSharePeerConnection) {
        adminDesktopSharePeerConnection.close();
        adminDesktopSharePeerConnection = null;
        console.log('管理员桌面共享WebRTC连接已关闭');
    }
    
    // 清空桌面共享ICE候选队列
    adminDesktopShareIceCandidateQueue = [];
    console.log('管理员桌面共享ICE候选队列已清空');
    
    // 重置状态
    adminDesktopShareState = 'idle';
    activeDesktopShareSession = null;
    currentDesktopShareSessionId = null;
    
    console.log('管理员桌面共享资源清理完成');
}

// 更新管理员桌面共享按钮
function updateAdminDesktopShareButton(state) {
    const desktopShareBtn = document.getElementById('adminDesktopShareBtn');
    const desktopShareBtnText = document.getElementById('adminDesktopShareBtnText');
    const rejectBtn = document.getElementById('adminRejectCallBtn');
    
    if (!desktopShareBtn || !desktopShareBtnText || !rejectBtn) return;
    
    // 更新状态变量
    adminDesktopShareState = state;
    console.log('管理员桌面共享状态已更新为:', state);
    
    switch (state) {
        case 'idle':
            desktopShareBtn.style.display = 'none';
            rejectBtn.style.display = 'none';
            break;
        case 'incoming':
            desktopShareBtn.style.display = 'inline-block';
            desktopShareBtn.style.background = '#4caf50';
            desktopShareBtnText.textContent = '接听桌面共享';
            rejectBtn.style.display = 'inline-block';
            break;
        case 'connected':
            desktopShareBtn.style.display = 'inline-block';
            desktopShareBtn.style.background = '#f44336';
            desktopShareBtnText.textContent = '结束桌面共享';
            rejectBtn.style.display = 'none';
            break;
    }
}

// 重置管理员桌面共享状态
function resetAdminDesktopShareState() {
    console.log('开始重置管理员桌面共享状态');
    
    adminDesktopShareState = 'idle';
    activeDesktopShareSession = null;
    currentDesktopShareSessionId = null;
    console.log('已重置桌面共享状态变量');
    
    stopAdminDesktopShareRingtone(); // 确保桌面共享铃声停止
    console.log('已停止桌面共享铃声');
    
    // 直接清理资源，不调用cleanupAdminDesktopShare函数
    console.log('开始清理管理员桌面共享资源');
    
    // 关闭桌面共享弹窗
    closeDesktopSharePopup();
    
    // 清理桌面共享流
    if (adminDesktopShareLocalStream) {
        adminDesktopShareLocalStream.getTracks().forEach(track => track.stop());
        adminDesktopShareLocalStream = null;
        console.log('管理员桌面共享流已清理');
    }
    
    // 关闭桌面共享WebRTC连接
    if (adminDesktopSharePeerConnection) {
        adminDesktopSharePeerConnection.close();
        adminDesktopSharePeerConnection = null;
        console.log('管理员桌面共享WebRTC连接已关闭');
    }
    
    // 清空桌面共享ICE候选队列
    adminDesktopShareIceCandidateQueue = [];
    console.log('管理员桌面共享ICE候选队列已清空');
    
    console.log('管理员桌面共享资源清理完成');
    
    // 如果有排队的桌面共享，处理下一个
    if (incomingDesktopShareSessions.size > 0) {
        console.log('活跃桌面共享结束，处理队列中的下一个桌面共享');
        processNextIncomingDesktopShare();
    } else {
        // 没有排队的桌面共享，完全重置
        console.log('没有排队的桌面共享，完全重置状态');
        updateAdminDesktopShareButton('idle');
        updateSessionCallStatus();
    }
    
    console.log('管理员桌面共享状态重置完成');
}

// 处理下一个待接听的桌面共享
function processNextIncomingDesktopShare() {
    if (incomingDesktopShareSessions.size > 0) {
        // 获取下一个桌面共享
        const nextSessionId = incomingDesktopShareSessions.values().next().value;
        currentDesktopShareSessionId = nextSessionId;
        
        updateAdminDesktopShareButton('incoming');
        playAdminDesktopShareRingtone();
        
        console.log('切换到下一个桌面共享:', nextSessionId, '还有', incomingDesktopShareSessions.size - 1, '个待接听');
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg(`切换到下一个桌面共享，还有 ${incomingDesktopShareSessions.size - 1} 个待接听`, {
                icon: 1,
                time: 2000
            });
        }
        
        // 更新所有排队用户的位置
        updateDesktopShareQueuePositions();
    } else {
        // 没有排队的桌面共享，直接重置状态，不调用resetAdminDesktopShareState函数
        console.log('没有排队的桌面共享，直接重置状态');
        
        // 保存当前会话ID，用于清理
        const sessionIdToClean = currentDesktopShareSessionId;
        
        // 重置状态
        adminDesktopShareState = 'idle';
        activeDesktopShareSession = null;
        currentDesktopShareSessionId = null;
        
        // 从待接听列表中移除当前会话
        if (sessionIdToClean) {
            incomingDesktopShareSessions.delete(sessionIdToClean);
            console.log('从待接听列表中移除会话:', sessionIdToClean);
        }
        
        // 更新UI状态
        updateAdminDesktopShareButton('idle');
        updateSessionCallStatus();
        
        // 添加调试日志
        console.log('桌面共享状态重置后 - activeDesktopShareSession:', activeDesktopShareSession, 'incomingDesktopShareSessions:', Array.from(incomingDesktopShareSessions));
        
        console.log('管理员桌面共享资源清理完成');
    }
    
    updateSessionCallStatus();
}

// 更新桌面共享队列中所有用户的位置
function updateDesktopShareQueuePositions() {
    console.log('更新桌面共享队列位置，当前队列:', Array.from(incomingDesktopShareSessions));
    
    let position = 1;
    for (const sessionId of incomingDesktopShareSessions) {
        if (sessionId !== currentDesktopShareSessionId) {
            // 发送更新的队列位置给用户
            adminSocket.emit('desktop_share_queue_status', {
                session_id: sessionId,
                status: 'queued',
                position: position,
                message: position === 1 ? 
                    '您是下一位，请保持等待...' : 
                    `当前有 ${position - 1} 人在您前面排队，请稍候...`
            });
            position++;
        }
    }
}

// 播放管理员桌面共享铃声
function playAdminDesktopShareRingtone() {
    if (!adminAudioContext) {
        console.log('音频上下文未初始化，跳过桌面共享铃声');
        return;
    }
    
    try {
        console.log('开始播放管理员桌面共享铃声');
        
        // 创建铃声音频
        const oscillator = adminAudioContext.createOscillator();
        const gainNode = adminAudioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(adminAudioContext.destination);
        
        // 设置铃声参数
        oscillator.frequency.setValueAtTime(800, adminAudioContext.currentTime);
        oscillator.frequency.setValueAtTime(600, adminAudioContext.currentTime + 0.1);
        oscillator.frequency.setValueAtTime(800, adminAudioContext.currentTime + 0.2);
        
        gainNode.gain.setValueAtTime(0.3, adminAudioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, adminAudioContext.currentTime + 0.3);
        
        oscillator.start(adminAudioContext.currentTime);
        oscillator.stop(adminAudioContext.currentTime + 0.3);
        
        // 循环播放铃声
        adminDesktopShareRingtone = setInterval(() => {
            if (adminDesktopShareState === 'incoming') {
                const oscillator = adminAudioContext.createOscillator();
                const gainNode = adminAudioContext.createGain();
                
                oscillator.connect(gainNode);
                gainNode.connect(adminAudioContext.destination);
                
                oscillator.frequency.setValueAtTime(800, adminAudioContext.currentTime);
                oscillator.frequency.setValueAtTime(600, adminAudioContext.currentTime + 0.1);
                oscillator.frequency.setValueAtTime(800, adminAudioContext.currentTime + 0.2);
                
                gainNode.gain.setValueAtTime(0.3, adminAudioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(0.01, adminAudioContext.currentTime + 0.3);
                
                oscillator.start(adminAudioContext.currentTime);
                oscillator.stop(adminAudioContext.currentTime + 0.3);
            }
        }, 300);
        
        console.log('管理员桌面共享铃声开始播放');
        
    } catch (error) {
        console.error('播放管理员桌面共享铃声失败:', error);
    }
}

// 停止管理员桌面共享铃声
function stopAdminDesktopShareRingtone() {
    if (adminDesktopShareRingtone) {
        clearInterval(adminDesktopShareRingtone);
        adminDesktopShareRingtone = null;
        console.log('管理员桌面共享铃声已停止');
    }
}

// 创建管理员桌面共享WebRTC连接
async function createAdminDesktopSharePeerConnection() {
    console.log('创建管理员桌面共享WebRTC连接');
    
    try {
        // 创建RTCPeerConnection
        adminDesktopSharePeerConnection = new RTCPeerConnection({
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' },
                { urls: 'stun:stun1.l.google.com:19302' }
            ]
        });
        
        // 设置远程流处理
        adminDesktopSharePeerConnection.ontrack = function(event) {
            console.log('收到桌面共享流:', event.streams);
            if (event.streams && event.streams[0]) {
                console.log('桌面共享流轨道数量:', event.streams[0].getTracks().length);
                
                // 创建桌面共享弹窗
                createDesktopSharePopup(event.streams[0]);
                
                console.log('桌面共享弹窗已创建');
            } else {
                console.error('没有收到桌面共享流');
            }
        };
        
        // 处理ICE候选
        adminDesktopSharePeerConnection.onicecandidate = function(event) {
            if (event.candidate) {
                console.log('发送桌面共享ICE候选给用户');
                adminSocket.emit('desktop_share_ice_candidate', {
                    session_id: currentDesktopShareSessionId,
                    candidate: event.candidate,
                    sender: 'admin'
                });
            }
        };
        
        // 处理连接状态变化
        adminDesktopSharePeerConnection.onconnectionstatechange = function() {
            console.log('桌面共享连接状态:', adminDesktopSharePeerConnection.connectionState);
            if (adminDesktopSharePeerConnection.connectionState === 'connected') {
                console.log('桌面共享连接已建立');
            } else if (adminDesktopSharePeerConnection.connectionState === 'failed') {
                console.log('桌面共享连接失败');
                // 直接清理资源，不调用cleanupAdminDesktopShare函数
                console.log('开始清理管理员桌面共享资源');
                
                // 停止桌面共享铃声
                stopAdminDesktopShareRingtone();
                
                // 关闭桌面共享弹窗
                closeDesktopSharePopup();
                
                // 清理桌面共享流
                if (adminDesktopShareLocalStream) {
                    adminDesktopShareLocalStream.getTracks().forEach(track => track.stop());
                    adminDesktopShareLocalStream = null;
                    console.log('管理员桌面共享流已清理');
                }
                
                // 关闭桌面共享WebRTC连接
                if (adminDesktopSharePeerConnection) {
                    adminDesktopSharePeerConnection.close();
                    adminDesktopSharePeerConnection = null;
                    console.log('管理员桌面共享WebRTC连接已关闭');
                }
                
                // 清空桌面共享ICE候选队列
                adminDesktopShareIceCandidateQueue = [];
                console.log('管理员桌面共享ICE候选队列已清空');
                
                // 重置状态
                adminDesktopShareState = 'idle';
                activeDesktopShareSession = null;
                currentDesktopShareSessionId = null;
                
                console.log('管理员桌面共享资源清理完成');
            }
        };
        
        console.log('管理员桌面共享WebRTC连接创建成功');
        
    } catch (error) {
        console.error('创建管理员桌面共享WebRTC连接失败:', error);
        throw error;
    }
}

// 结束桌面共享函数已在上方定义，此处删除重复定义

// 创建桌面共享弹窗
function createDesktopSharePopup(stream) {
    console.log('创建桌面共享弹窗');
    
    // 移除现有的桌面共享弹窗
    const existingPopup = document.getElementById('desktopSharePopup');
    if (existingPopup) {
        existingPopup.remove();
    }
    
    // 创建弹窗容器
    const popup = document.createElement('div');
    popup.id = 'desktopSharePopup';
    popup.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 80%;
        max-width: 1200px;
        height: 80%;
        max-height: 800px;
        background: white;
        border: 2px solid #007bff;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        z-index: 10000;
        display: flex;
        flex-direction: column;
    `;
    
    // 创建弹窗标题栏
    const header = document.createElement('div');
    header.style.cssText = `
        background: #007bff;
        color: white;
        padding: 10px 15px;
        border-radius: 6px 6px 0 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: bold;
        cursor: move;
    `;
    header.innerHTML = `
        <span>🖥️ 桌面共享 - ${currentDesktopShareSessionId ? '用户' + currentDesktopShareSessionId.substring(0, 8) : '未知用户'}</span>
        <div class="desktop-share-controls">
            <button class="desktop-share-control-btn" onclick="minimizeDesktopShare()" title="最小化">—</button>
            <button class="desktop-share-control-btn" onclick="maximizeDesktopShare()" title="最大化">🗖</button>
            <button class="desktop-share-control-btn" onclick="fullscreenDesktopShare()" title="全屏">⛶</button>
            <button class="desktop-share-control-btn" onclick="closeDesktopSharePopup()" title="关闭">✕</button>
        </div>
    `;
    
    // 创建视频容器
    const videoContainer = document.createElement('div');
    videoContainer.style.cssText = `
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #000;
        border-radius: 0 0 6px 6px;
        overflow: hidden;
    `;
    
    // 创建视频元素
    const video = document.createElement('video');
    video.id = 'adminDesktopShareRemoteVideo';
    video.autoplay = true;
    video.controls = true;
    video.style.cssText = `
        width: 100%;
        height: 100%;
        object-fit: contain;
    `;
    
    // 设置视频流
    video.srcObject = stream;
    
    // 添加视频事件监听器
    video.onloadedmetadata = function() {
        console.log('桌面共享视频元数据已加载');
    };
    
    video.onplay = function() {
        console.log('桌面共享视频开始播放');
    };
    
    video.onerror = function(error) {
        console.error('桌面共享视频播放错误:', error);
    };
    
    // 添加点击事件处理，点击视频时暂停/播放
    video.onclick = function() {
        if (video.paused) {
            video.play().then(() => {
                console.log('桌面共享视频已播放');
                // 添加播放状态的CSS类
                video.classList.remove('paused');
                video.classList.add('playing');
            }).catch(err => {
                console.error('播放视频失败:', err);
            });
        } else {
            video.pause();
            console.log('桌面共享视频已暂停');
            // 添加暂停状态的CSS类
            video.classList.remove('playing');
            video.classList.add('paused');
        }
    };
    
    // 添加鼠标样式，提示用户可以点击
    video.style.cursor = 'pointer';
    
    // 添加悬停效果
    video.onmouseenter = function() {
        if (!video.paused) {
            video.style.opacity = '0.9';
        }
    };
    
    video.onmouseleave = function() {
        if (!video.paused) {
            video.style.opacity = '1';
        }
    };
    
    // 监听播放状态变化
    video.onplay = function() {
        console.log('桌面共享视频开始播放');
        video.classList.remove('paused');
        video.classList.add('playing');
    };
    
    video.onpause = function() {
        console.log('桌面共享视频已暂停');
        video.classList.remove('playing');
        video.classList.add('paused');
    };
    
    // 组装弹窗
    videoContainer.appendChild(video);
    popup.appendChild(header);
    popup.appendChild(videoContainer);
    
    // 添加到页面
    document.body.appendChild(popup);
    
    // 保存视频元素引用
    adminDesktopShareRemoteVideo = video;
    
    // 初始化拖拽功能
    setTimeout(() => {
        initDesktopShareDrag();
    }, 100);
    
    console.log('桌面共享弹窗已创建并添加到页面');
}

// 关闭桌面共享弹窗
function closeDesktopSharePopup() {
    console.log('关闭桌面共享弹窗');
    
    const popup = document.getElementById('desktopSharePopup');
    if (popup) {
        popup.remove();
    }
    
    if (adminDesktopShareRemoteVideo) {
        adminDesktopShareRemoteVideo.srcObject = null;
        adminDesktopShareRemoteVideo = null;
    }
    
    // 不调用endDesktopShare()，避免循环调用
    console.log('桌面共享弹窗已关闭');
}

// 强制清理所有桌面共享状态
function forceClearDesktopShareStates() {
    console.log('强制清理所有桌面共享状态');
    
    // 重置所有状态变量
    adminDesktopShareState = 'idle';
    activeDesktopShareSession = null;
    currentDesktopShareSessionId = null;
    
    // 清空待接听列表
    incomingDesktopShareSessions.clear();
    
    // 停止铃声
    stopAdminDesktopShareRingtone();
    
    // 关闭弹窗
    closeDesktopSharePopup();
    
    // 更新UI
    updateAdminDesktopShareButton('idle');
    updateSessionCallStatus();
    
    console.log('所有桌面共享状态已强制清理');
}

// 最小化桌面共享弹窗
function minimizeDesktopShare() {
    const popup = document.getElementById('desktopSharePopup');
    if (popup) {
        if (popup.classList.contains('minimized')) {
            // 如果已经最小化，则恢复正常大小
            restoreDesktopShare();
        } else {
            // 移除其他状态类
            popup.classList.remove('maximized');
            popup.classList.remove('fullscreen');
            // 添加最小化类
            popup.classList.add('minimized');
            console.log('桌面共享弹窗已最小化');
        }
    }
}

// 最大化桌面共享弹窗
function maximizeDesktopShare() {
    const popup = document.getElementById('desktopSharePopup');
    if (popup) {
        if (popup.classList.contains('maximized')) {
            // 恢复正常大小
            restoreDesktopShare();
        } else {
            // 最大化 - 移除其他状态类，添加最大化类
            popup.classList.remove('minimized');
            popup.classList.remove('fullscreen');
            popup.classList.add('maximized');
            console.log('桌面共享弹窗已最大化');
        }
    }
}

// 恢复桌面共享弹窗正常大小
function restoreDesktopShare() {
    const popup = document.getElementById('desktopSharePopup');
    if (popup) {
        popup.classList.remove('maximized');
        popup.classList.remove('minimized');
        popup.classList.remove('fullscreen');
        console.log('桌面共享弹窗已恢复正常大小');
    }
}

// 桌面共享弹窗拖拽功能
let isDragging = false;
let dragStartX = 0;
let dragStartY = 0;
let dragStartLeft = 0;
let dragStartTop = 0;

// 初始化桌面共享弹窗拖拽
function initDesktopShareDrag() {
    const popup = document.getElementById('desktopSharePopup');
    if (!popup) return;
    
    const header = popup.querySelector('div[style*="background: #007bff"]');
    if (!header) return;
    
    header.addEventListener('mousedown', function(e) {
        // 允许在最小化状态下拖拽，但不允许在最大化、浏览器窗口全屏或真正全屏状态下拖拽
        if (popup.classList.contains('maximized') || 
            popup.classList.contains('fullscreen') || 
            document.fullscreenElement) return;
        
        isDragging = true;
        dragStartX = e.clientX;
        dragStartY = e.clientY;
        
        const rect = popup.getBoundingClientRect();
        dragStartLeft = rect.left;
        dragStartTop = rect.top;
        
        document.addEventListener('mousemove', handleDesktopShareDrag);
        document.addEventListener('mouseup', stopDesktopShareDrag);
    });
}

function handleDesktopShareDrag(e) {
    if (!isDragging) return;
    
    const popup = document.getElementById('desktopSharePopup');
    if (!popup || 
        popup.classList.contains('maximized') || 
        popup.classList.contains('fullscreen') || 
        document.fullscreenElement) return;
    
    const deltaX = e.clientX - dragStartX;
    const deltaY = e.clientY - dragStartY;
    
    const newLeft = dragStartLeft + deltaX;
    const newTop = dragStartTop + deltaY;
    
    popup.style.left = newLeft + 'px';
    popup.style.top = newTop + 'px';
    popup.style.transform = 'none';
}

function stopDesktopShareDrag() {
    isDragging = false;
    document.removeEventListener('mousemove', handleDesktopShareDrag);
    document.removeEventListener('mouseup', stopDesktopShareDrag);
}

// 全屏桌面共享弹窗
function fullscreenDesktopShare() {
    const popup = document.getElementById('desktopSharePopup');
    if (popup) {
        if (document.fullscreenElement) {
            // 退出全屏
            document.exitFullscreen().then(() => {
                console.log('桌面共享弹窗已退出全屏');
            }).catch(err => {
                console.error('退出全屏失败:', err);
            });
        } else {
            // 进入全屏
            popup.requestFullscreen().then(() => {
                console.log('桌面共享弹窗已进入全屏');
            }).catch(err => {
                console.error('进入全屏失败:', err);
                // 如果全屏API不可用，回退到浏览器窗口全屏
                popup.classList.remove('maximized');
                popup.classList.remove('minimized');
                popup.classList.add('fullscreen');
                console.log('回退到浏览器窗口全屏模式');
            });
        }
    }
}

// 监听全屏状态变化
document.addEventListener('fullscreenchange', function() {
    const popup = document.getElementById('desktopSharePopup');
    if (popup) {
        if (!document.fullscreenElement) {
            // 退出全屏时，移除CSS全屏类
            popup.classList.remove('fullscreen');
            console.log('检测到全屏状态变化，已退出全屏');
        }
    }
});

// 添加键盘事件监听
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        if (document.fullscreenElement) {
            // 如果当前有元素处于全屏状态，退出全屏
            document.exitFullscreen().then(() => {
                console.log('通过ESC键退出全屏');
            }).catch(err => {
                console.error('退出全屏失败:', err);
            });
        } else {
            // 检查是否有桌面共享弹窗处于浏览器窗口全屏状态
            const popup = document.getElementById('desktopSharePopup');
            if (popup && popup.classList.contains('fullscreen')) {
                popup.classList.remove('fullscreen');
                console.log('通过ESC键退出浏览器窗口全屏');
            }
        }
    }
});

// 删除会话
window.deleteSession = function(sessionId) {
    layer.confirm('确定要删除这个会话吗？删除后将无法恢复！', {
        icon: 3,
        title: '确认删除'
    }, function(index) {
        layer.close(index);
        
        // 发送删除会话请求
        if (adminSocket && adminSocket.connected) {
            adminSocket.emit('delete_session', {session_id: sessionId});
        }
        
        layer.msg('删除成功', {icon: 1});
    });
};

// 语音回拨
window.voiceCallBack = function(sessionId) {
    console.log('语音回拨功能已实现，会话ID:', sessionId);
    callbackUser(sessionId)
    // layer.msg('语音回拨功能待实现', {icon: 1, time: 2000});
};

// 视频回拨
window.videoCallBack = function(sessionId) {
    console.log('视频回拨功能已实现，会话ID:', sessionId);
    callbackVideoUser(sessionId);
    // layer.msg('视频回拨功能待实现', {icon: 1, time: 2000});
};

// 桌面共享回拨
window.desktopShareCallBack = function(sessionId) {
    console.log('桌面共享回拨功能待实现，会话ID:', sessionId);
    layer.msg('桌面共享回拨功能待实现', {icon: 1, time: 2000});
};

// 视频回拨用户
function callbackVideoUser(sessionId) {
    console.log('管理员视频回拨用户，会话ID:', sessionId);
    
    if (!adminSocket || !adminSocket.connected) {
        console.log('管理员端未连接，无法视频回拨');
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('连接已断开，无法视频回拨', {icon: 2});
        }
        return;
    }
    
    try {
        // 设置管理员为视频回拨状态
        adminVideoCallState = 'calling';
        currentVideoCallSessionId = sessionId;
        updateAdminVideoCallButton('calling');
        
        // 播放视频回拨铃声
        playAdminVideoRingtone();
        console.log('开始播放管理员视频回拨铃声');
        
        // 发送视频回拨请求
        adminSocket.emit('admin_video_call_callback', {
            session_id: sessionId,
            type: 'callback_request'
        });
        
        console.log('管理员视频回拨请求已发送:', sessionId);
        
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('正在视频回拨用户，请等待用户接听...', {icon: 1, time: 3000});
        }
        
        // 设置30秒超时
        adminVideoCallTimeoutTimer = setTimeout(() => {
            if (adminVideoCallState === 'calling') {
                console.log('视频回拨超时，用户未接听');
                handleAdminVideoCallTimeout();
            }
        }, 30000); // 30秒超时
        
    } catch (error) {
        console.error('视频回拨用户失败:', error);
        if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
            layer.msg('视频回拨失败', {icon: 2});
        }
    }
}

// 处理管理员视频通话超时
function handleAdminVideoCallTimeout() {
    console.log('管理员视频通话超时');
    
    // 停止视频铃声
    stopAdminVideoRingtone();
    
    // 重置状态
    resetAdminVideoCallState();
    
    // 发送超时通知
    if (adminSocket && adminSocket.connected && currentVideoCallSessionId) {
        adminSocket.emit('admin_video_call_timeout', {
            session_id: currentVideoCallSessionId
        });
    }
    
    if (typeof layer !== 'undefined' && typeof layer.msg === 'function') {
        layer.msg('视频回拨超时，用户未接听', {icon: 2, time: 2000});
    }
}
</script>
</body>
</html> 